In Rust, variables are immutable by default, meaning they cannot be changed once they are assigned a value. To declare an immutable variable, you use the let keyword. On the other hand, if you want to create a mutable variable that can be changed after its initial assignment, you use the let mut keyword. Let’s explore the differences between let and let mut with examples:
Immutable variable (let):
fn main() {
let x = 5;
println!("The value of x is: {}", x);
// This line would cause a compilation error because x is immutable.
// x = 6;
}
In the example above, the variable x is declared as immutable using the let keyword. If you try to change the value of x, the compiler will throw an error.
Mutable variable (let mut):
fn main() {
let mut y = 5;
println!("The value of y is: {}", y);
y = 6; // This is allowed since y is mutable.
println!("The value of y is now: {}", y);
}
In this example, the variable y is declared as mutable using the let mut keyword. This allows you to change the value of y without causing a compilation error.
In summary, the main difference between let and let mut is that let declares an immutable variable that cannot be changed once assigned, while let mut declares a mutable variable that can be modified after its initial assignment.