By default, variables in Rust are immutable. When a variable is immutable, once a value is bound to a name, you can’t change that value. These checks are made at compile-time.
Variables can be made mutable by adding
mut in front of the variable name.
Difference between variables and constants
Constants are declared using the
const keyword and the type of the value must be annotated. You aren’t allowed to use
mut with constants. Constants are always immutable.
Constants must be set at compile-time through a constant expression, i.e. constant cannot be a result of a function call or any other value computed at runtime.
let x = 5; // an immutable variable let x = x + 1; // shadowing
In Rust, you can declare a new variable with the same name as a previous variable. The first variable here is shadowed by the second, i.e. the second variable’s value is what appears when the variable is used.
Shadowing is different from
mut, because we’ll get a compile-time error if accidentally try to reassign to this variable without using the
let keyword. By using
let we can perform a few operations on a value but have the variables be immutable after those transformations have been completed.
The other difference between
mut and shadowing is that because we’re effectively creating a new variable when we use the
let keyword again, we can change the type of the value but reuse the same name.
let spaces = " "; let spaces = spaces.len(); // type changed to u32
Note that the following is not allowed, because Rust doesn’t allow mutating a variable’s type.
let spaces = " "; spaces = spaces.len(); // no 'let', type change illegal