Ownership is Rust's most unique feature. It enables Rust to make memory safety guarantees without needing a garbage collector. The rules are: each value has a single owner, when the owner goes out of scope the value is dropped, and there can only be one owner at a time.
Rust
Beginner
15 min read
Ownership in Rust
Example
fn main() {
// Ownership example
let s1 = String::from("hello");
let s2 = s1; // s1 is MOVED to s2
// println!("{s1}"); // ERROR: s1 no longer valid
println!("{s2}"); // OK
// Clone to copy the data
let s3 = s2.clone();
println!("{s2} and {s3}"); // both valid
// Borrowing - references
let s4 = String::from("world");
let len = calculate_length(&s4); // borrow, not move
println!("{s4} has length {len}"); // s4 still valid
// Mutable references
let mut s5 = String::from("hello");
change(&mut s5);
println!("{s5}");
}
fn calculate_length(s: &String) -> usize {
s.len() // s is borrowed, not owned
} // s goes out of scope but doesn't drop the data
fn change(s: &mut String) {
s.push_str(", world");
}