Ownership
- Each value in Rust has a variable that’s called its owner.
- There can only be one owner at a time.
- When the owner goes out of scope, the value will be dropped.
// this function takes ownership of `v` fn print_vector(v: Vec<i32>) { println!("{:?}", v); // `v` is deallocated here } fn main() { let v = vec![1, 2, 3]; print_vector(v); // `v` is moved, transferring ownership // trying to use `v` here is a compile error // v.len(); }
This style of resource management is similar to how RAII types like unique_ptr work in C++.
Unlike C++, Rust does not have move constructors. A move is always just a memcpy.
Simple types like integers can still be used after being moved. This behaviour is controlled by the Copy trait.