Mutable reference
- Rust course
- Beginner
- Lesson 49/115
- 4 min
Take a mutable reference with &mut.
Mutable references
To change a borrowed value, &mut is used. The variable itself must also be mut:
fn unlem_ekle(s: &mut String) {
s.push('!');
}
let mut selam = String::from("Merhaba");
unlem_ekle(&mut selam);
println!("{selam}"); // Merhaba!To change Copy types such as numbers, dereference with *: fn artir(n: &mut i32) { *n += 1; }.
Why exclusivity?
Changing a value from two places at once leads to data races and inconsistent state. Rust prevents this at compile time:
let mut v = vec![1, 2];
let a = &mut v;
// let b = &mut v; // error E0499: a second &mut
a.push(3);
println!("{:?}", v);This rule only applies while the references are alive; after a is used for the last time, a new &mut can be taken (non-lexical lifetimes).
Practice Increment the counter
Let fn artir(n: &mut i32, adim: i32) do *n += adim. For let mut sayac = 10;, call artir(&mut sayac, 5) twice and print the result.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn artir(n: &mut i32, adim: i32) {
*n += adim;
}
fn main() {
let mut sayac = 10;
artir(&mut sayac, 5);
artir(&mut sayac, 5);
println!("{}", sayac);
}Expected output
20
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How many <code>&mut</code> references can exist at the same time?
- None
- One Correct answer
- Unlimited
- Two
Explanation: A mutable reference is exclusive: only one can exist at a time, and no other reference may exist meanwhile.
2 Change the value
fn ikiye_katla(n: &mut i32) {
____n *= 2;
}
fn ikiye_katla(n: &mut i32) {
*n *= 2;
}
Explanation: *n dereferences the reference; the change is written to the real variable.
3 Code and result
| Term | Meaning |
|---|---|
&mut s |
Mutable borrow |
*n += 1 |
Dereferences and changes |
Two &mut at once |
E0499 |
let s (no mut) + &mut s |
Compile error |