Introduction
Mutable variables let you change the value stored in them after you create them. This helps when you want to update information as your program runs.
Mutable variables let you change the value stored in them after you create them. This helps when you want to update information as your program runs.
let mut variable_name = initial_value;
Use mut right after let to make a variable mutable.
Without mut, variables are read-only and cannot be changed.
count starting at 0, then changes it to 5.let mut count = 0; count = 5;
name is not mutable, so trying to change it will cause an error.let name = "Alice"; // name = "Bob"; // This will cause an error because name is not mutable
temperature starts at 20 and then increases by 5.let mut temperature = 20; temperature = temperature + 5;
This program shows a mutable variable score starting at 0, then changing to 10, printing both values.
fn main() {
let mut score = 0;
println!("Initial score: {}", score);
score = 10;
println!("Updated score: {}", score);
}Remember to use mut only when you need to change the variable.
Rust helps prevent bugs by making variables immutable by default.
Mutable variables let you change values after creating them.
Use let mut to declare a mutable variable.
Without mut, variables cannot be changed.
let to declare variables, but by default they are immutable.mut after let makes the variable mutable.let mut for mutable variables [OK]let mut makes variables changeable [OK]x with value 5 in Rust?let comes first, then mut to mark mutability.let mut x = 5; which is correct. Others have wrong order or invalid keywords.let mut variable = value; [OK]let mut in that order [OK]fn main() {
let mut count = 1;
count = count + 2;
println!("{}", count);
}count starts at 1 and is mutable.count becomes 3.fn main() {
let x = 10;
x = 20;
println!("{}", x);
}x is declared without mut, so it is immutable.x = 20; tries to change an immutable variable, causing a compile error.mut to allow variable reassignment [OK]fn main() {
let mut counter = 0;
increment(&mut counter);
increment(&mut counter);
println!("{}", counter);
}
fn increment(count: &mut i32) {
*count += 1;
}let mut counter = 0;.increment takes a mutable reference and increases the value by 1 each call.let mut and mutable references to update variables [OK]Pass the test and this pattern moves unknown