Mutability with mut
mut tells Rust that a value is allowed to change later on.In this page:
Declaring a Mutable Variable
Adding the mut keyword after let allows the variable's value to be changed later in the program. Without mut, any attempt to reassign the variable is a compile-time error.
Example: Declaring a Mutable Variable
fn main() {
let mut score = 0;
println!("Starting score: {}", score);
score = 10;
println!("Updated score: {}", score);
}
Login to try C/C++/Java/PHP code in the editor
Mutating in a Loop
Mutable variables are especially useful inside loops, where a value needs to accumulate or change on every iteration, such as a running total.
Example: Mutating in a Loop
fn main() {
let mut total = 0;
for n in 1..=5 {
total += n;
}
println!("Total: {}", total);
}
Login to try C/C++/Java/PHP code in the editor
Type Stays Fixed
Even though a mut variable's value can change, its type is fixed for the life of the binding. You cannot store a string in a variable that was first assigned an integer.
Example: Type Stays Fixed
fn main() {
let mut count: i32 = 1;
count = count + 1;
println!("count is now {}", count);
}
Login to try C/C++/Java/PHP code in the editor
Immutable by Default, Opt-in Mutability
Rust chose immutable-by-default so that, when you read code, a plain let binding is a guarantee its value never changes -- making programs easier to reason about, especially when multiple parts of code share data.
Example: Immutable by Default, Opt-in Mutability
fn main() {
let fixed = 100;
let mut adjustable = 100;
adjustable += 1;
println!("fixed: {}, adjustable: {}", fixed, adjustable);
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting the
mutkeyword and then getting a confusing compiler error when trying to reassign a variable. - Assuming
mutlets you change a variable's type, when it only allows changing its value, not its type. - Marking everything
mutout of habit instead of only the variables that actually need to change.
- Adding
mutbefore a variable name allows its value to be reassigned later. - The type of a mutable variable cannot change, only its value.
- Rust encourages immutability by default to make code easier to reason about and safer to run concurrently.
- The compiler will warn if a
mutvariable is never actually mutated.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: