Understanding Rust Ownership
Rust's ownership system is one of its most distinctive features. It enables memory safety without a garbage collector.
The Three Rules
- 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.
Borrowing
Instead of transferring ownership, you can borrow a reference to the data.
fn main() {
let s = String::from("hello");
let len = calculate_length(&s);
println!("Length of '{}' is {}.", s, len);
}
This is a powerful concept that eliminates data races at compile time.
Next: Understanding Lifetimes