Borrowing and references: & and &mut
In the previous lesson you saw that passing a String to a function moves it and you lose it. Returning the value every time would be annoying. The solution is to lend: a reference lets you use a value without taking its ownership. It is written with &. It is like lending a book to a friend: the book is still yours, he only reads it and gives it back. Here you will learn the two kinds of borrow and the rules the compiler enforces to avoid memory errors and data races.
Shared references: &T
A & reference lets you read the value, but not modify it. You can have as many shared references as you want at the same time, because nobody changes anything. The function receives &String, and when calling it you pass &variable. When the function ends the reference disappears, but the original value stays with its owner. Creating a reference is called borrowing.
fn length_of(text: &String) -> usize {
text.len()
} // the reference ends; nothing is freed
fn main() {
let name = String::from("Rustacean");
let n = length_of(&name);
println!("{name} has {n} bytes");
let a = &name;
let b = &name; // many shared borrows are fine
println!("{a} {b}");
}Mutable references: &mut T
To modify a borrowed value you need a mutable reference, &mut. Two requirements: the original variable must be mut and the call must write &mut variable. The golden rule is this: at any time you can have a single mutable reference OR any number of shared references, but never both at once. It sounds strict, but it is exactly what avoids data races and the "I changed something while someone else was reading it" bugs. Rust checks it at compile time.
fn add_exclamation(text: &mut String) {
text.push('!');
}
fn main() {
let mut message = String::from("hello");
add_exclamation(&mut message);
add_exclamation(&mut message);
println!("{message}");
let r1 = &message;
let r2 = &message;
println!("{r1} {r2}"); // last use of r1 and r2
let r3 = &mut message; // OK: r1 and r2 are not used anymore
r3.push_str("?");
println!("{r3}");
}Notice the end of the example: although r1 and r2 are still in scope, the compiler knows they are not used after the println!, so it allows creating r3. This feature is called NLL (non-lexical lifetimes): the borrow lasts until the last use, not until the closing brace. Now let us see the case that does fail: mixing a mutable reference with a shared one that is still used.
// Does NOT compile on purpose: mutable + shared borrow at the same time
fn main() {
let mut v = String::from("data");
let first = &v;
let second = &mut v; // error: cannot borrow `v` as mutable
second.push('x');
println!("{first}");
}Dangling references
In C it is easy to return a pointer to a local variable that no longer exists (a dangling pointer). In Rust the compiler prevents it: a reference can never outlive the value it points to. If you try to return &String from a function that created the String inside, you get "missing lifetime specifier" or "returns a reference to data owned by the current function". The fix is to return the full String (moving ownership) instead of a reference. You will study formal lifetimes in week 6.
fn build_greeting(name: &str) -> String {
let text = format!("Hello, {name}!");
text // return the owned String, not &text
}
fn main() {
let g = build_greeting("Ana");
println!("{g}");
}fn count_vowels(text: &String) -> usize {
text.chars().filter(|c| matches!(c.to_ascii_lowercase(), 'a' | 'e' | 'i' | 'o' | 'u')).count()
}
fn make_upper(text: &mut String) {
*text = text.to_uppercase();
}
fn main() {
let mut word = String::from("education");
println!("{}", count_vowels(&word));
make_upper(&mut word);
println!("{word} -> {}", count_vowels(&word));
}Проверьте себя
Вопрос 1 из 4How many &mut references can exist at once for the same value?
✎ Мои заметки
Сохранено только в этом браузере. Войдите, чтобы хранить в аккаунте.0/5000 символов