Ownership

Programming Languages · Rust Control Flow & Ownership · 14 min

Rust's big idea, gently: moving values, cloning them, and lending them out with & and &mut.

Every value has one owner

Here's Rust's big idea. Every value has exactly one owner: the variable that holds it. When you hand a String to another variable, it moves. The new variable owns it, and the old one can't be used anymore:

let a = String::from("hi");
let b = a; // a moved into b

That's how Rust cleans up memory for you, safely.

  • Move first into a new variable second.

  • Print second. (Curious? Try printing first too, read Rust's error, then remove that line.)

clone makes a copy

Want to keep both? Call .clone(). It makes a full copy, so each variable owns its own String:

let a = String::from("hi");
let b = a.clone(); // a is still yours

Small simple values like i32 and bool are copied automatically, so they never move.

  • Create backup as a clone of original.

  • Print original: notes, then backup: notes, using the two variables.

Borrowing with &

Copying everything would be slow. Usually you just lend a value instead: put & in front of it. That's called borrowing. The function can read it, and you get it back afterwards:

fn shout(text: &String) {
    println!("{}!", text);
}

let word = String::from("hey");
shout(&word);
println!("{}", word); // still mine
  • Write fn show(title: &String) that prints Reading and the title, like Reading Dune.

  • In main, lend book to it with show(&book), before the last line.

Changing through &mut

A plain & borrow is read-only. To let a function change what you lend, use &mut. The variable itself must be mut too:

fn cheer(text: &mut String) {
    text.push_str("!");
}

let mut s = String::from("yay");
cheer(&mut s); // s is now "yay!"

push_str adds text to the end of a String.

  • Write fn add_milk(list: &mut String) that adds ", milk" to the end of list.

  • Call it with add_milk(&mut list), so the program prints eggs, milk.

Put it together: a shared playlist

One function changes the playlist (&mut), another only looks at it (&). The playlist stays owned by main the whole time.

  • Write fn add_song(list: &mut String, song: &str) that adds ", " and then song to list.

  • Write fn show(list: &String) that prints Playlist: and the list.

  • In main, add "Song B" and "Song C", then show it: Playlist: Song A, Song B, Song C.

More in Rust Control Flow & Ownership

Previous: Control Flow · Next: Structs