BeginnerLesson 5 of 16
Ownership: Owning & Moving – Rust
The central idea of Rust: every value has exactly one owner.
Three rules form the heart of Rust: (1) Every value has exactly one owner. (2) There can only be one owner at a time. (3) When the owner goes out of scope, the value is freed (drop). That is why Rust needs no garbage collector: the cleanup is already determined at compile time.
fn main() {
let s1 = String::from("hello");
let s2 = s1; // move: s1 hands ownership over to s2
// println!("{s1}"); // error: borrow of moved value: s1
println!("{s2}");
let s3 = s2.clone(); // explicit deep copy
println!("{s2} {s3}");
}Simple fixed-size types (numbers, bool, char, tuples of these) implement the Copy trait: they are copied on assignment instead of moved. String and Vec own heap memory and are therefore moved.
fn main() {
let a = 5;
let b = a; // copy: both stay valid
println!("{a} {b}");
}Ownership is also transferred when you call a function. If you want to keep using the value afterwards, you return it, or (better) you just borrow it (next lesson).
fn verbrauche(s: String) {
println!("{s}");
} // s is freed here
fn gib_zurueck(s: String) -> String {
s
}
fn main() {
let text = String::from("Hi");
verbrauche(text);
// println!("{text}"); // error: text was moved
let neu = gib_zurueck(String::from("back"));
println!("{neu}");
}TipRemember: move is the normal case, copy is the exception for small values, and clone() is the deliberate (and possibly expensive) copy. If you keep writing
.clone() just to placate the compiler, borrowing is usually the better solution.Warning
let t = vec![1, 2, 3]; for x in t { ... } also moves t into the loop. After that, t is gone. Use for x in &t to only borrow.