Summary - Borrowing
- Rust course
- Beginner
- Lesson 53/115
- 5 min
Write a function that increments a counter via & and &mut references.
Borrowing summary
&T reads without taking ownership; &mut T modifies (the variable must be mut). The rule: at any time either many &T or a single &mut T. A reference can't outlive the value it points to. Function signatures state the intent: T consumes, &T/&[T]/&str read, &mut T modifies.
Borrowing habits
Practical rules: ask for the weakest access possible in parameters (&str > &String > String); keep references short-lived; when you get a borrow-checker error, first look for a small value you could copy, then try reordering the operations. .clone() is the last resort, but it's fine for small values.
Practice Longest word
Write fn en_uzun(kelimeler: &[&str]) -> usize; it returns the character count of the longest word (chars().count() and max). Print the result for ["go", "rust", "çiçekçi"].
Starter code
fn main() {
// buraya yaz
}Sample solution
fn en_uzun(kelimeler: &[&str]) -> usize {
kelimeler.iter().map(|k| k.chars().count()).max().unwrap_or(0)
}
fn main() {
println!("{}", en_uzun(&["go", "rust", "çiçekçi"]));
}Expected output
7
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which of these compiles?
- None
- let mut s = String::new(); let r = &mut s; r.push('a'); println!("{s}"); Correct answer
- let mut s = String::new(); let r = &mut s; println!("{s}"); r.push('a');
- let s = String::new(); let r = &mut s;
Explanation: In the first, r is last used in push and then s is read; in the second, s is read while r is still going to be used (E0502); in the third, s isn't mut.
2 Mutable borrow
let mut liste = vec![1];
ekle(____ liste);
let mut liste = vec![1];
ekle(&mut liste);
Explanation: Since the function will change the list, &mut liste is passed.
3 Group summary
| Term | Meaning |
|---|---|
&T |
Shared read |
&mut T |
Exclusive write |
Borrow checker |
Checks the rules |
Lifetime |
A reference can't outlive the value |