Mutability with mut
- Rust course
- Beginner
- Lesson 8/115
- 4 min
Update variables with the mut keyword.
Mutability with mut
Variables whose value will change later are declared with let mut:
let mut sayac = 0;
sayac += 1;
sayac += 1;
println!("{sayac}"); // 2The word mut tells the reader "this value will change". An unnecessary mut produces a compiler warning, nudging code toward as few mutable variables as possible.
Compound assignment
For mutable numbers the +=, -=, *=, /= and %= operators are used. Rust has no ++ or --; you write x += 1. Integer overflow panics in debug builds and wraps in release builds; for explicit behavior there are methods such as checked_add and wrapping_add.
Practice Counter
Declare let mut toplam = 0;. Do toplam += i; in a for i in 1..=5 loop and print the result.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn main() {
let mut toplam = 0;
for i in 1..=5 {
toplam += i;
}
println!("{}", toplam);
}Expected output
15
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What happens with <code>let mut x = 5; x = "beş";</code>?
- Compile error: the type can't change Correct answer
- x becomes "beş"
- It warns
- A run-time error
Explanation: mut only allows the value to change, not the type. For a new value of a different type, shadowing is used.
2 Mutable
let ____ toplam = 0;
toplam += 5;
let mut toplam = 0;
toplam += 5;
Explanation: let mut allows the variable to be changed later.
3 Code and result
| Term | Meaning |
|---|---|
let x = 1; x = 2; |
Compile error |
let mut x = 1; x = 2; |
x = 2 |
x++ |
Not in Rust |
x += 1 |
Increments by one |