Ownership and borrowing
The ownership rules
Three rules, and everything else follows. Each value has an owner (a variable). There is only one owner at a time. When the owner goes out of scope, the value is dropped.
fn main() { let a = String::from("ACME Bank"); let b = a; // la propriété passe de a à b : c'est un move // println!("{a}"); // erreur : borrow of moved value: `a` println!("{b}");} // b sort de portée ici : la mémoire de la String est libéréeWhy a move and not a copy? A String lives on the heap. If a and b both pointed to the same text, the memory would be freed twice at the end of the scope. Rust forbids it by invalidating a. In Java the GC solves this at the cost of pauses; here, it is settled at compile time.
fn main() { let x = 42; let y = x; // i32 est Copy : x reste utilisable println!("{x} {y}"); let s1 = String::from("EUR"); let s2 = s1.clone(); // copie explicite du contenu println!("{s1} {s2}");}.clone().Passing a value to a function follows the same rules: the function becomes the owner, and the caller can no longer use it afterwards.
fn print_name(name: String) { println!("{name}");} // name est libérée ici fn main() { let counterparty = String::from("ACME Bank"); print_name(counterparty); // print_name(counterparty); // erreur : use of moved value}Your turn
This program does not compile. Fix it without adding .clone(): reordering two lines is enough.
fn archive(report: String) { println!("archivé : {report}");} fn main() { let report = String::from("EE report"); archive(report); println!("taille : {}", report.len());}After the call to archive, the String has a new owner.
fn archive(report: String) { println!("archivé : {report}");} fn main() { let report = String::from("EE report"); println!("taille : {}", report.len()); archive(report);}We read the length while main still owns the value, then hand it over. The compiler reasons about statement order: a move only invalidates the variable from the point where it happens.