BeginnerLesson 6 of 16
References & Borrowing – Rust
Borrowing values with & and &mut, and the rules of the borrow checker.
A reference (&T) borrows a value without taking ownership. The owner stays valid once the function is done.
fn laenge(s: &String) -> usize {
s.len()
}
fn main() {
let s = String::from("hello");
let n = laenge(&s);
println!("{s} has {n} characters"); // s is still usable
}To make changes you need a mutable reference &mut T, and the variable itself must be mut.
fn anhaengen(s: &mut String) {
s.push_str(" World");
}
fn main() {
let mut t = String::from("Hello");
anhaengen(&mut t);
println!("{t}"); // Hello World
}The borrow checker enforces two rules: at any point in time there are either any number of &T or exactly one &mut T, never both. In addition, no reference may outlive the value it points to. This makes data races and dangling pointers impossible.
fn main() {
let mut v = vec![1, 2, 3];
let erstes = &v[0]; // immutable reference
v.push(4); // error: cannot borrow v as mutable,
// because it is also borrowed as immutable
println!("{erstes}");
}Why? push might move the vector in memory, and erstes would then point to nothing. Since non-lexical lifetimes, all that counts is until when the reference is last *used*. If println! comes before push, the code compiles.
fn main() {
let mut v = vec![1, 2, 3];
let erstes = v[0]; // copy of the value, not a reference
v.push(4);
println!("{erstes} {:?}", v); // 1 [1, 2, 3, 4]
let text = String::from("Hello World");
let wort: &str = &text[0..5]; // string slice
println!("{wort}");
}TipUse
&str instead of &String and &[T] instead of &Vec<T> as parameters: the function then accepts more types (deref coercion) and is more flexible.