Rust Tutorial · Ownership and Borrowing · Lesson 9 of 29
Rust Ownership
The three ownership rules, moves, clones, and Copy types: how Rust manages memory without a garbage collector.
The rules
- Each value has one owner (a variable).
- There can only be one owner at a time.
- When the owner goes out of scope, the value is dropped (its memory freed).
Assigning or passing a heap value like String moves ownership; the old variable can't be used any more.
fn consume(text: String) {
println!("consumed: {text}");
} // text is dropped here
fn main() {
let a = String::from("order-42");
let b = a; // ownership moves to b
// println!("{a}"); // error: borrow of moved value: `a`
consume(b); // moves into the function
// println!("{b}"); // error: b was moved too
println!("both a and b are gone; the memory was freed once");
}
Output
consumed: order-42 both a and b are gone; the memory was freed once
Run this on your computer — see “Get Started” for setup.
Clone and Copy
.clone() makes a deep copy explicitly. Simple values stored on the stack (integers, bool, char, tuples of
them) implement Copy and are copied instead of moved.
fn main() {
let original = String::from("config");
let copy = original.clone(); // explicit deep copy
println!("{original} and {copy}");
let x = 5;
let y = x; // i32 is Copy: x is still usable
println!("{x} and {y}");
}
Output
config and config 5 and 5
Run this on your computer — see “Get Started” for setup.
Test yourself
What happens to s1 after let s2 = s1; when s1 is a String?
s1 and s2 share the strings1 is moved and can no longer be useds1 is copieds1 becomes empty but usable
Show answer
Answer: s1 is moved and can no longer be used