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
firstinto a new variablesecond.Print
second. (Curious? Try printingfirsttoo, 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
backupas a clone oforiginal.Print
original: notes, thenbackup: 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 printsReadingand the title, likeReading Dune.In
main, lendbookto it withshow(&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 oflist.Call it with
add_milk(&mut list), so the program printseggs, 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 thensongtolist.Write
fn show(list: &String)that printsPlaylist: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