by default the variables are immutable unless you make it mutable with mut
fn main () {
let x = 5;
let mut y = 6;
println! {"Variable x equals to {x} and cannot be changed."};
println! {"Variable y equals to {y} and can be changed."};
y = 8;
println!("New value of variable y equals to {y}.")
}
A variable can be shadowed by using the same variable’s name and use it with let.
The second variable overshadows the first variable until either it itself is shadowed or the scope ends.
fn main() {
let x = 5;
println!("The value of x is {x}.");
let x = x + 2;
println!("The new value of x is {x} and overshadows the previous value.");
{
let x = x * 2;
println!("The value of x in inner scope is {x}.");
}
println!("The value of x outside the inner scope is again {x}");
}
Shadowing differs from marking a variable as mut:
as the value cannot be changed without using the let
the variable is still immutable after transformation with let
Shadowing can also change the type of the value
fn main() {
let spaces = " ";
println!(" Variable spaces is a string.");
let spaces = spaces.len();
println!("The type of variable spaces is now a number and spaces equals to {spaces}.");
}