Skip to content
binshelf/ rust

Search lessons

Type a Rust, TypeScript or C# term, like Option, null or E0382.

    Compare Rust with

    Lessons

    Module 3 · Borrowing & slices

    3.3Choosing parameter types: T, &T, &mut T or Box<T>

    A decision guide for every function signature you write in Rust, what to return, and the signatures that look right when you're new to Rust but aren't.

    About 30 minutesIntermediate

    On this page
    1. Concept map
    2. The signature says what the function does
    3. How your parameters map to Rust
    4. When Box<T> is the right type
    5. Small values, optional values and “anything that can…”
    6. What to return
    7. Which one should I use?
    8. Signatures to avoid
    9. What to return
    10. Under the hood
    11. Common pitfalls
    12. Try it yourself

    Concept map

    Concept map: how your language and Rust handle each idea in this lesson
    ConceptTypeScriptC#Rust
    A function that reads its argumentTakes the object; it's sharedTakes the object (class) or a copy (struct); in for a large struct&T
    A function that changes its argumentTakes the object and changes itTakes the object (class), or ref for a struct or a variable&mut T
    A function that keeps its argumentTakes the object and stores the referenceTakes the object and stores the referenceT: ownership moves in
    Text and list parametersstring, readonly T[]string, ReadOnlySpan<T>, IReadOnlyList<T>&str, &[T]
    BoxingNot a concept; every object is on the heapImplicit: a struct passed as object or an interface is copied to the heapNever implicit: you write Box::new(value), or call a function whose return type says Box
    What to returnAny objectAny object; ref returns are restrictedAn owned value, or a borrow of a parameter; never a borrow of a local

    Every Rust function signature answers a question that TypeScriptC# mostly leaves unspoken: what will this function do with its argument? Read it, change it, or keep it? In TypeScript, every object parameter is shared, so the answer is “any of those”.In C#, a class parameter is shared, so the answer is “any of those”. In Rust, the parameter type says which, and the compiler holds both sides to it. This lesson is the guide for choosing. Its tables are the part to come back to.

    The signature says what the function does

    Here’s a playlist with three functions: one reads it, one changes it, one stores it. In TypeScriptC#, all three take a plain Playlist, and you have to read the bodies to know which does what. In Rust, the signatures tell you.

    TypeScript
    playlist.ts
    type Playlist = { name: string; songs: string[] };
    
    function describe(playlist: Playlist): string {
      return `${playlist.name}: ${playlist.songs.length} songs`;
    }
    
    function addSong(playlist: Playlist, title: string): void {
      playlist.songs.push(title);
    }
    
    function archive(shelf: Playlist[], playlist: Playlist): void {
      shelf.push(playlist);
    }
    
    const playlist: Playlist = { name: "Focus", songs: [] };
    addSong(playlist, "Weightless");
    addSong(playlist, "Clair de Lune");
    console.log(describe(playlist));
    
    const shelf: Playlist[] = [];
    archive(shelf, playlist);
    console.log(`${shelf.length} archived`);
    C#
    Playlist.cs
    var playlist = new Playlist("Focus");
    AddSong(playlist, "Weightless");
    AddSong(playlist, "Clair de Lune");
    Console.WriteLine(Describe(playlist));
    
    var shelf = new List<Playlist>();
    Archive(shelf, playlist);
    Console.WriteLine($"{shelf.Count} archived");
    
    static string Describe(Playlist playlist) => $"{playlist.Name}: {playlist.Songs.Count} songs";
    
    static void AddSong(Playlist playlist, string title) => playlist.Songs.Add(title);
    
    static void Archive(List<Playlist> shelf, Playlist playlist) => shelf.Add(playlist);
    
    class Playlist(string name)
    {
        public string Name { get; } = name;
        public List<string> Songs { get; } = [];
    }
    Rust
    struct Playlist {
        name: String,
        songs: Vec<String>,
    }
    
    fn describe(playlist: &Playlist) -> String {
        format!("{}: {} songs", playlist.name, playlist.songs.len())
    }
    
    fn add_song(playlist: &mut Playlist, title: String) {
        playlist.songs.push(title);
    }
    
    fn archive(shelf: &mut Vec<Playlist>, playlist: Playlist) {
        shelf.push(playlist);
    }
    
    fn main() {
        let mut playlist = Playlist {
            name: String::from("Focus"),
            songs: Vec::new(),
        };
        add_song(&mut playlist, String::from("Weightless"));
        add_song(&mut playlist, String::from("Clair de Lune"));
        println!("{}", describe(&playlist));
    
        let mut shelf = Vec::new();
        archive(&mut shelf, playlist); // `playlist` moves onto the shelf
        println!("{} archived", shelf.len());
    }

    Output

    Focus: 2 songs
    1 archived
    • describe only reads, so it borrows: &Playlist.
    • add_song changes the playlist, so it borrows mutably: &mut Playlist. It also keeps the title, so it takes an owned String. If it took &str, it would have to copy the text with .to_string() to store it; taking String lets a caller who already has one hand it over with no copy.
    • archive keeps the playlist, so it takes Playlist by value. After the call, main can’t use playlist anymore: it belongs to the shelf. In TypeScriptC#, playlist and shelf[0] would be two names for one object, and a later change through either would show up in both.

    Mental model shiftThe signature is the contract

    In TypeScriptC#, “does this function keep a reference to my object?” is a question for the docs or the source code. In Rust, it’s in the type. A function that takes &T can’t keep it after it returns (unless its signature says so with lifetime annotations, which Module 11 covers), a function that takes &mut T is the only one touching it during the call, and a function that takes T owns it from then on.

    How your parameters map to Rust

    TypeScript has one way to pass an object, so the mapping depends on what the function does with it:

    What the TypeScript function doesRust parameterNote
    Reads an object&TNo copy, and the caller keeps ownership. The function can’t change the value.
    Changes an object&mut TMarked at the call site too (&mut playlist), and no other reference to the value can exist during the call.
    Stores an object, in a list or a fieldTOwnership moves in. The caller can’t use the value afterwards unless it passed a clone.
    Takes a number or a booleani32, f64, boolCopied in both languages.
    Takes a string or an array it only reads&str, &[T]A borrowed view, so nothing is copied.

    Boxing is a word you’ll meet in Rust, but TypeScript never makes you think about it: every object already lives on the heap behind a reference, and the primitive wrapper objects from Stack vs. heap are the nearest thing.

    C# is already close to Rust here, because it distinguishes copies from shared references:

    C#RustNote
    A struct parameter (copied)T for a Copy typeSmall values are copied in both languages.
    in parameter&TA read-only reference, so a large value isn’t copied. In Rust, &T is the everyday choice for any type, not just large structs.
    ref parameter&mut TBoth are marked at the call site. Rust’s is exclusive: no other reference to the value can exist during the call.
    out parameterA return valueRust has no out. Return a tuple, a struct or an Option instead.
    A class parameter&T, &mut T or TC# shares every object. Rust makes you choose.

    Boxing is where the same word means different things. In C#, passing a struct where an object or an interface is expected silently copies it into a new heap object:

    Boxing.cs
    var point = new Point(1, 2);
    object boxed = point; // boxing: copies point into a new heap object
    point.X = 10;
    Console.WriteLine($"{point.X} {((Point)boxed).X}"); // 10 1: the box has its own copy
    
    record struct Point(int X, int Y);

    Rust never puts a value on the heap behind your back. Box<T> is an ordinary type: an owned pointer to one value on the heap. You get one by writing Box::new(value) (or calling a function whose return type says Box), and when the Box goes out of scope, the value is freed. Passing a struct where “anything that implements a trait” is expected doesn’t box it either: generics and &dyn Trait work without any heap allocation, much as C# generics with an interface constraint avoid boxing a struct. So in Rust, Box<T> is a deliberate choice, and as a parameter type it’s rarely the right one.

    When Box<T> is the right type

    There are three good reasons to put a value in a Box:

    1. A recursive type. A type that contains itself needs a pointer somewhere, or it would be infinitely large.
    2. A trait object: a value whose concrete type isn’t known at compile time, such as a list of different shapes, Vec<Box<dyn Shape>>. Module 9 covers traits and dyn.
    3. A large value you move around a lot. Moving a Box copies one pointer instead of the whole value. You’ll rarely need this.

    Here’s the first case: a tree of numbers. TypeScriptC# doesn’t need anything special, because every object variable is already a reference. In Rust, a Tree stored directly inside a Tree would make the type infinitely large, so the children go in boxes.

    TypeScript
    tree.ts
    type Tree = { kind: "leaf"; value: number } | { kind: "node"; left: Tree; right: Tree };
    
    function sum(tree: Tree): number {
      return tree.kind === "leaf" ? tree.value : sum(tree.left) + sum(tree.right);
    }
    
    const tree: Tree = {
      kind: "node",
      left: { kind: "leaf", value: 1 },
      right: {
        kind: "node",
        left: { kind: "leaf", value: 2 },
        right: { kind: "leaf", value: 3 },
      },
    };
    console.log(sum(tree));
    C#
    Tree.cs
    Tree tree = new Node(new Leaf(1), new Node(new Leaf(2), new Leaf(3)));
    Console.WriteLine(Sum(tree));
    
    static int Sum(Tree tree) => tree switch
    {
        Leaf leaf => leaf.Value,
        Node node => Sum(node.Left) + Sum(node.Right),
        _ => throw new InvalidOperationException("Unknown tree"),
    };
    
    abstract record Tree;
    record Leaf(int Value) : Tree;
    record Node(Tree Left, Tree Right) : Tree;
    Rust
    enum Tree {
        Leaf(i32),
        Node(Box<Tree>, Box<Tree>),
    }
    
    fn sum(tree: &Tree) -> i32 {
        match tree {
            Tree::Leaf(value) => *value,
            Tree::Node(left, right) => sum(left) + sum(right),
        }
    }
    
    fn main() {
        let tree = Tree::Node(
            Box::new(Tree::Leaf(1)),
            Box::new(Tree::Node(Box::new(Tree::Leaf(2)), Box::new(Tree::Leaf(3)))),
        );
        println!("{}", sum(&tree));
    }

    Output

    6

    The box is in the type, Node(Box<Tree>, Box<Tree>), not in the function. sum still takes &Tree. Inside the match, left is a &Box<Tree>, and sum(left) works because Rust converts a &Box<T> to a &T automatically (deref coercion, the same rule that turns &String into &str). So a function that reads a boxed value never needs to mention Box.

    Common pitfallBox doesn't mean boxing

    C# boxing is implicit, copies a value type to the heap, and needs a cast to copy it back out. Rust’s Box<T> is explicit, moves the value in, leaving no stale original behind, and you use the value through it directly: boxed.x and boxed.len() just work, and *boxed gives you the value itself.

    Small values, optional values and “anything that can…”

    Copy types: pass by value. Numbers, bool, char and small structs that implement Copy are copied as cheaply as a reference would be. Take them by value: fn area(width: f64, height: f64) -> f64. A &i32 parameter only adds a * you have to write.

    Optional borrows: Option<&T>, not &Option<T>. Here’s a function that reads a user’s optional address. Option is Rust’s version of T | undefinedT?; Module 6 covers it.

    TypeScript
    city.ts
    type Address = { city: string };
    type User = { name: string; address?: Address };
    
    function describeCity(address: Address | undefined): string {
      return address?.city ?? "unknown";
    }
    
    const ada: User = { name: "Ada", address: { city: "London" } };
    const grace: User = { name: "Grace" };
    console.log(`${ada.name}: ${describeCity(ada.address)}`);
    console.log(`${grace.name}: ${describeCity(grace.address)}`);
    C#
    City.cs
    var ada = new User("Ada", new Address("London"));
    var grace = new User("Grace", null);
    Console.WriteLine($"{ada.Name}: {DescribeCity(ada.Address)}");
    Console.WriteLine($"{grace.Name}: {DescribeCity(grace.Address)}");
    
    static string DescribeCity(Address? address) => address?.City ?? "unknown";
    
    record Address(string City);
    record User(string Name, Address? Address);
    Rust
    struct Address {
        city: String,
    }
    
    struct User {
        name: String,
        address: Option<Address>,
    }
    
    fn describe_city(address: Option<&Address>) -> &str {
        match address {
            Some(address) => &address.city,
            None => "unknown",
        }
    }
    
    fn main() {
        let ada = User {
            name: String::from("Ada"),
            address: Some(Address {
                city: String::from("London"),
            }),
        };
        let grace = User {
            name: String::from("Grace"),
            address: None,
        };
        println!("{}: {}", ada.name, describe_city(ada.address.as_ref()));
        println!("{}: {}", grace.name, describe_city(grace.address.as_ref()));
    }

    Output

    Ada: London
    Grace: unknown

    .as_ref() turns a &Option<Address> into an Option<&Address> without copying anything. Why not take &Option<Address> directly? Because then the caller must own an Option<Address>. A caller holding a plain &Address, say from a list, would have to clone the address into a new Option just to call you. Option<&Address> accepts Some(&address), None and user.address.as_ref(). For text, Option<String> has .as_deref(), which gives you an Option<&str>.

    “Anything that can…”: impl Trait. When a function should accept any type with some ability, like “anything that can be printed”, use impl Trait. It’s like a TypeScript parameter typed with an interfacea C# generic method with a where T : ISomething constraint:

    use std::fmt::Display;
    
    fn log(value: impl Display) {
        println!("[log] {value}");
    }
    
    fn main() {
        log(42);
        log("ready");
        log(3.5);
    }

    The same ownership choices apply: value: impl Display takes ownership, value: &impl Display borrows. Module 9 covers traits and generics.

    What to return

    Return owned values. A function that builds a String, a Vec or a struct hands it to the caller, who becomes the owner. That’s a move, so it’s cheap: no heap data is copied.

    What you can’t do is return a reference to something the function created. In TypeScriptC#, returning a new object is always fine, because the garbage collector keeps it alive. In Rust, a function’s local variables are dropped when it returns, so a reference to one would dangle:

    fn make_greeting(name: &str) -> &str {
        let greeting = format!("Hello, {name}!");
        &greeting
    }

    Rust doesn't compile this: error E0515

    error[E0515]: cannot return reference to local variable `greeting`
     --> main.rs:3:5
      |
    3 |     &greeting
      |     ^^^^^^^^^ returns a reference to data owned by the current function

    The fix is to return the String itself, moving it out to the caller:

    fn make_greeting(name: &str) -> String {
        format!("Hello, {name}!")
    }
    
    fn main() {
        println!("{}", make_greeting("Ada"));
    }

    Returning a reference is fine when it borrows from a parameter, like describe_city above or first_word in Slices. The compiler then makes sure the caller keeps the argument alive while it uses the result. How it knows which parameter the result borrows from is the subject of lifetimes, in Module 11.

    Which one should I use?

    This is the table to bookmark. Pick the first row that matches what the function does with the argument.

    What (signature)WhenWhyHow (call site)
    value: &TThe function only reads the value. The default.No copy, and the caller keeps ownership and can keep using it.describe(&playlist). If you already hold a &T, pass it as is.
    text: &strThe function reads text.Accepts a &String, a literal and a slice of either.greet("Ada"), greet(&name), greet(&name[..3]).
    items: &[T]The function reads a list.Accepts a &Vec<T>, an array and a range of either.total(&scores), total(&scores[1..4]).
    value: &mut TThe function changes the caller’s value in place.The caller sees the change, and the call site shows it. No one else can touch the value during the call.Declare let mut playlist; call add_song(&mut playlist, ...).
    items: &mut [T] or &mut Vec<T>The function changes a list: &mut [T] to change elements, &mut Vec<T> to add or remove them.Asks for exactly the power it needs.sort_scores(&mut scores), archive(&mut shelf, playlist).
    value: TThe function keeps the value (stores it in a struct or collection), consumes it, or returns a changed version.Ownership moves in, so the function doesn’t need to copy it. The caller decides whether to give it up or pass a clone.archive(&mut shelf, playlist); to keep yours, archive(&mut shelf, playlist.clone()).
    title: StringThe function stores text.A caller with a String moves it in, with no copy. Taking &str would force a copy inside.add_song(&mut playlist, String::from("Blue")), or title.to_string().
    count: i32, f64, bool, charAny small Copy value.Copying a few bytes costs the same as passing a pointer, and there’s no * to write.area(3.0, 4.0). The caller’s value stays usable.
    value: Option<&T>The function reads a value that might be missing.Accepts Some(&value), None or an existing option via .as_ref(), without cloning.describe_city(user.address.as_ref()).
    value: impl TraitThe function accepts any type with some ability (“anything that can be printed”).One function for many types, with no boxing. Module 9 covers it.log(42), log("ready"). Use &impl Trait to borrow instead.
    value: Box<T>Rarely. The function stores a value that’s already boxed, typically a Box<dyn Trait> going into a collection.Moves the existing heap allocation in, with no copy.shapes.push(Box::new(circle)). To read a boxed value, take &T instead.

    Rule of thumb: start with &T (&str, &[T] for text and lists). Switch to &mut T if the function must change the caller’s value, and to T if it must keep it. Pass Copy types by value. Reach for Box in types, not in parameters.

    For the common cases, the same rule as questions to ask in order; the first “yes” gives the parameter type:

    Which parameter type?
    1. Does the function keep the value (store it in a struct or collection), consume it, or return a changed version?

      Yes

      Take TOwnership moves in. For text it stores, take String. A caller who wants to keep theirs passes a clone.

      No
    2. Does it change the caller's value in place?

      Yes

      Take &mut TFor a list: &mut [T] to change elements, &mut Vec<T> to add or remove them.

      No
    3. Is it a small Copy value: a number, bool, char or a small Copy struct?

      Yes

      Take it by value: i32, f64, bool, charCopying a few bytes costs the same as passing a pointer, and there's no * to write.

      No
    4. Does it read text or a list?

      Yes

      Take &str or &[T]Not &String or &Vec<T>: these also accept literals, arrays and slices.

      No
    5. Otherwise: Take &T, the default. It accepts a boxed value too, so don't write &Box<T>.

    The table covers the rest: Option<&T> for a value that might be missing, impl Trait for “anything that can…”, and the rare Box<T>.

    Signatures to avoid

    Instead ofWriteBecause
    &String&str&str also accepts literals and slices. Clippy flags &String (ptr_arg).
    &Vec<T>&[T]&[T] also accepts arrays and slices. Clippy flags &Vec<T> (ptr_arg).
    &Box<T>&TOne pointer hop instead of two, and callers without a box can call it. Clippy flags it (borrowed_box).
    &Option<T>Option<&T>Callers with a plain &T don’t have to build an Option.
    &i32, &f64, &booli32, f64, boolThey’re Copy: passing by value is as cheap and needs no *.
    name: &str, then .to_string() to store itname: StringLet the caller decide whether to allocate.

    What to return

    The question that decides most return types is where the value comes from:

    Which return type?
    1. Is the result one of a few fixed strings written in the code?

      Yes

      Return &'static strLiterals live for the whole program, so nothing is allocated.

      No
    2. Is the result part of an argument: a field, a word, an element?

      Yes

      Return &T, &str or &[T] (or Option<&T> for a lookup)No copy. The compiler ties the result to that argument, so the caller keeps the argument alive while it uses the result.

      No
    3. Otherwise: The function builds or computes the value: return it owned, as T (String, Vec<T>, a struct). A borrow of a local would dangle (E0515).

    What (return type)WhenWhyHow
    T (String, Vec<T>, a struct)The function builds or computes a new value. The default.The caller becomes the owner. Returning is a move, so no heap data is copied.fn make_greeting(name: &str) -> String.
    &T, &str, &[T]The result is part of an argument: a field, a word, an element.No copy. The compiler ties the result to that argument.fn first_word(text: &str) -> &str.
    &'static strThe result is one of a few fixed strings.Literals live for the whole program, so nothing is allocated.fn status_label(code: u16) -> &'static str.
    Option<&T>A lookup that might find nothing.Borrows the match if there is one. Module 6 covers Option.scores.first(), map.get(&key).
    Box<dyn Trait> or impl TraitThe result is “some type with this ability”.impl Trait for one concrete type, Box<dyn Trait> when it varies at run time. Module 9 covers both.fn make_shape(kind: &str) -> Box<dyn Shape>.

    Methods follow the same rules, spelled &self, &mut self and self; Structs & impl blocks covers them.

    Under the hood

    Each choice has a fixed, small cost at the call:

    println!("String: {}", size_of::<String>());
    println!("&String: {}", size_of::<&String>());
    println!("&str: {}", size_of::<&str>());
    println!("Box<String>: {}", size_of::<Box<String>>());

    On a 64-bit machine, that prints 24, 8, 16 and 8 bytes. Passing a String by value copies its 24-byte header (pointer, length, capacity), never the text. A &T or a Box<T> is one pointer; a &str or &[T] is a pointer plus a length. The difference between &T, &mut T and T is mostly about who may do what, checked at compile time, not about speed.

    Why is &Box<T> wasteful? It’s a pointer to a pointer:

    let scores = Box::new([10, 20, 30]);
    let via_box: &Box<[i32; 3]> = &scores;
    let direct: &[i32; 3] = &scores;
    println!("{} {}", via_box[0], direct[0]);
    &Box<T> vs &TOn the stack, scores is a Box holding one pointer to a heap block with the numbers 10, 20 and 30. via_box is a &Box: its pointer leads to the scores variable on the stack, so reading a number takes two hops. direct is a plain reference: its pointer leads straight to the heap block, one hop.StackHeapscores: Box<[i32; 3]>ptrvia_box: &Box<[i32; 3]>ptrdirect: &[i32; 3]ptrheap102030
    &Box<T> vs &T. On the stack, scores is a Box holding one pointer to a heap block with the numbers 10, 20 and 30. via_box is a &Box: its pointer leads to the scores variable on the stack, so reading a number takes two hops. direct is a plain reference: its pointer leads straight to the heap block, one hop.

    &scores can become either type: Rust converts &Box<T> to &T wherever a &T is expected. So a &T parameter accepts boxed and unboxed values alike, and gets there in one hop.

    And why does a recursive type need a Box at all? Without one, the compiler can’t work out its size:

    enum Tree {
        Leaf(i32),
        Node(Tree, Tree),
    }

    Rust doesn't compile this: error E0072

    error[E0072]: recursive type `Tree` has infinite size
     --> main.rs:1:1
      |
    1 | enum Tree {
      | ^^^^^^^^^
    2 |     Leaf(i32),
    3 |     Node(Tree, Tree),
      |          ---- recursive without indirection
      |
    help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to break the cycle
      |
    3 |     Node(Box<Tree>, Tree),
      |          ++++    +

    A Tree would contain two Trees, each containing two more, forever. Box<Tree> is always one pointer wide, so the size becomes finite. The compiler’s message suggests exactly that fix.

    Common pitfalls

    Common pitfall&Box<T> parameters shut out normal values

    A function that takes &Box<Song> can only be called with a boxed song. A caller with an ordinary Song can’t call it at all:

    struct Song {
        title: String,
    }
    
    fn print_title(song: &Box<Song>) {
        println!("{}", song.title);
    }
    
    fn main() {
        let song = Song {
            title: String::from("Blue"),
        };
        print_title(&song);
    }

    Rust doesn't compile this: error E0308

    error[E0308]: mismatched types
      --> main.rs:13:17
       |
    13 |     print_title(&song);
       |     ----------- ^^^^^ expected `&Box<Song>`, found `&Song`
       |     |
       |     arguments to this function are incorrect
       |
       = note: expected reference `&Box<Song>`
                  found reference `&Song`
    note: function defined here
      --> main.rs:5:4
       |
     5 | fn print_title(song: &Box<Song>) {
       |    ^^^^^^^^^^^ ----------------

    Take song: &Song. It accepts &song, and also &boxed_song, through deref coercion. Clippy flags &Box<T> parameters with the borrowed_box lint. A Box<T> parameter, without the &, is rarely better: it forces every caller to allocate, and clippy’s boxed_local lint flags it when the function doesn’t need the box.

    Common pitfallTaking ownership when you only read

    Coming from TypeScriptC#, it’s tempting to write fn describe(playlist: Playlist), because that’s what the signature looks like there. It compiles, but it moves the playlist into the function, which drops it at the end. The caller loses it:

    struct Playlist {
        name: String,
    }
    
    fn describe(playlist: Playlist) -> String {
        format!("Playlist {}", playlist.name)
    }
    
    fn main() {
        let playlist = Playlist {
            name: String::from("Focus"),
        };
        println!("{}", describe(playlist));
        println!("{}", describe(playlist));
    }

    Rust doesn't compile this: error E0382

    error[E0382]: use of moved value: `playlist`
      --> main.rs:14:29
       |
    10 |     let playlist = Playlist {
       |         -------- move occurs because `playlist` has type `Playlist`, which does not implement the `Copy` trait
    ...
    13 |     println!("{}", describe(playlist));
       |                             -------- value moved here
    14 |     println!("{}", describe(playlist));
       |                             ^^^^^^^^ value used here after move
       |
    note: consider changing this parameter type in function `describe` to borrow instead if owning the value isn't necessary
      --> main.rs:5:23
       |
     5 | fn describe(playlist: Playlist) -> String {
       |    --------           ^^^^^^^^ this parameter takes ownership of the value
       |    |
       |    in this function
    note: if `Playlist` implemented `Clone`, you could clone the value
      --> main.rs:1:1
       |
     1 | struct Playlist {
       | ^^^^^^^^^^^^^^^ consider implementing `Clone` for this type
    ...
    13 |     println!("{}", describe(playlist));
       |                             -------- you could clone this value

    Don’t fix this with .clone() at every call. Change the parameter to &Playlist and pass &playlist.

    Common pitfallReturning a borrow of something you just made

    If you build a String or Vec inside a function, return it as String or Vec<T>, not &str or &[T]. The local is dropped when the function returns, so a borrow of it would dangle, and the compiler reports E0515 (shown above). TypeScriptC# never raises this, because the garbage collector keeps the object alive.

    Try it yourself

    Exercise: port this to Rust

    Port this shopping cart to Rust. Choose each parameter type from the tables above: itemCount only reads the cart, addItem adds to it, and checkout should use the cart up, so it can’t be used after checking out.

    Starting code in TypeScript
    cart.ts
    type Cart = { items: string[] };
    
    function itemCount(cart: Cart): number {
      return cart.items.length;
    }
    
    function addItem(cart: Cart, item: string): void {
      cart.items.push(item);
    }
    
    function checkout(cart: Cart): string {
      return `Receipt: ${cart.items.join(", ")}`;
    }
    
    const cart: Cart = { items: [] };
    addItem(cart, "apple");
    addItem(cart, "pear");
    console.log(`${itemCount(cart)} items`);
    console.log(checkout(cart));
    Starting code in C#
    Cart.cs
    var cart = new Cart();
    AddItem(cart, "apple");
    AddItem(cart, "pear");
    Console.WriteLine($"{ItemCount(cart)} items");
    Console.WriteLine(Checkout(cart));
    
    static int ItemCount(Cart cart) => cart.Items.Count;
    
    static void AddItem(Cart cart, string item) => cart.Items.Add(item);
    
    static string Checkout(Cart cart) => $"Receipt: {string.Join(", ", cart.Items)}";
    
    class Cart
    {
        public List<string> Items { get; } = [];
    }

    Expected output

    2 items
    Receipt: apple, pear
    Show a hint

    item_count only reads the cart, add_item changes it and stores the text, and checkout uses the cart up. That gives &Cart, &mut Cart with a String, and Cart by value.

    Show a solution
    struct Cart {
        items: Vec<String>,
    }
    
    fn item_count(cart: &Cart) -> usize {
        cart.items.len()
    }
    
    fn add_item(cart: &mut Cart, item: String) {
        cart.items.push(item);
    }
    
    fn checkout(cart: Cart) -> String {
        format!("Receipt: {}", cart.items.join(", "))
    }
    
    fn main() {
        let mut cart = Cart { items: Vec::new() };
        add_item(&mut cart, String::from("apple"));
        add_item(&mut cart, String::from("pear"));
        println!("{} items", item_count(&cart));
        println!("{}", checkout(cart));
    }

    item_count borrows with &Cart. add_item takes &mut Cart because it pushes, and String because it keeps the item, so a caller with a String moves it in without a copy. checkout takes Cart by value: the cart is used up, and main can't touch it afterwards, which is exactly what checking out means.

    Saved in this browser only.