Ownership
The core rules
- Each value has one owner
- Only one owner at a time
- When the owner goes out of scope, the value is dropped
Move on assignment
Assigning a String moves ownership; the old name cannot be used.
let a = String::from("hello");
let b = a;
// println!("{a}"); // error: a was moved
println!("{b}");
Clone when you need a copy
clone deep-copies heap data so both names are valid.
let a = String::from("hello");
let b = a.clone();
println!("{a} {b}");
Copy types
Small stack types like integers implement Copy and duplicate automatically.
let x = 5;
let y = x;
println!("{x} {y}");
Comments
One comment per signed-in account. Comments are saved with this page’s URL.