What are mutable and immutable variables in Rust?
Rust defaults variable declaration to immutability, meaning unless you state otherwise, it assumes that what you’re creating should be treated like a constant. To facilitate this, the mut keyword can be used to indicate a variable should be mutable, an immutable object (unchangeable object) is an object whose state cannot be modified after it is created. This is in contrast to a mutable object (changeable object), which can be modified after it is created:Example with error
fn main() {
// This is an integer without the "mut" keyword, and therefore
// defaults to immutable. We will get a compiler error if we try
// to change this.
let intConst = 5;
// The "mut" keyword means we're "opting in" to mutability here,
// so "intVar" will act like a traditional variable. We can change it.
let mut intVar = 5;
intVar = 6;
intConst = 6; // error[E0384]: cannot assign twice to immutable variable `intConst`
println!("{}", intConst);
println!("{}", intVar);
}
Output
error[E0384]: cannot assign twice to immutable variable `intConst`
Fix Above example
To fix above example we will need to remove the line where we try to reassign the a value again:fn main() {
// This is an integer without the "mut" keyword, and therefore
// defaults to immutable. We will get a compiler error if we try
// to change this.
let intConst = 5;
// The "mut" keyword means we're "opting in" to mutability here,
// so "intVar" will act like a traditional variable. We can change it.
let mut intVar = 5;
intVar = 6;
//// We removed this line so we don't re-assign the value again after declaration.
println!("{}", intConst);
println!("{}", intVar);
}
Output
5
6
6