Ownership
1/14/2025
Ownership in Rust
Ownership is Rust’s most unique feature and enables memory safety without garbage collection.
Ownership Rules
- Each value has an owner
- Only one owner at a time
- Value is dropped when owner goes out of scope
Move Semantics
rust
fn main() {
let s1 = String::from("hello");
let s2 = s1; // s1 is moved to s2
// println!("{}", s1); // Error! s1 is no longer valid
println!("{}", s2); // OK
}Clone
rust
fn main() {
let s1 = String::from("hello");
let s2 = s1.clone(); // Deep copy
println!("s1 = {}, s2 = {}", s1, s2); // Both valid
}References and Borrowing
rust
fn main() {
let s = String::from("hello");
let len = calculate_length(&s); // Borrow s
println!("Length of '{}' is {}", s, len); // s still valid
}
fn calculate_length(s: &String) -> usize {
s.len()
}Mutable References
rust
fn main() {
let mut s = String::from("hello");
change(&mut s);
println!("{}", s); // "hello, world"
}
fn change(s: &mut String) {
s.push_str(", world");
}
Monkey Knows Wiki