Learn / Rust / Ownership and borrowing: the big idea
Rust, lesson 4 of 5
Ownership and borrowing: the big idea
Every value in Rust has exactly one owner. When the owner is finished, the value is cleaned up. Giving a value to another variable moves it:
fn main() {
let a = String::from("secret");
let b = a;
println!("{}", a);
}Rust refuses to build this.
After let b = a; the text belongs to b, so using a again is refused. This rule is how Rust frees memory exactly once. "Use after free" bugs, a classic cause of security holes in C and C++ programs, cannot happen.
To let a function look at a value without taking it, borrow it with &:
fn length(text: &String) -> usize {
text.len()
}
fn main() {
let name = String::from("Rust");
let n = length(&name);
println!("{} has {} letters", name, n);
}
To let a function change a value, lend it with &mut:
fn add_mark(text: &mut String) {
text.push('!');
}
fn main() {
let mut s = String::from("done");
add_mark(&mut s);
println!("{}", s);
}
The rule: at any moment, a value can have many readers (&) or one writer (&mut), never both. That is what stops two parts of a program from changing the same data at once.