Shadowing
When looking at the let variable we've seen that the value can be changed through the use of the mut
keyword. We can take this a couple steps further through reassignment and variable shadowing. Note that shadowing applies only to variables. Constants cannot be shadowed.
Reassignment
We can redefine the type and value of a variable by instantiating a new version after the first declaration.
// Set `foo` to take the value of `5` and the default `u64` type
let foo = 5;
// Reassign `foo` to be a `str` with the value of `Fuel`
let foo = "Fuel";
Variable Shadowing
If we do not want to alter the original variable but we'd like to temporarily reuse the variable name then we can use block scope to constrain the variable.
let foo = 5;
{
let foo = 42;
}
assert(foo == 5);
foo
is defined inside the curly brackets { }
and only exist inside the { .. }
scope; therefore, the original foo
variable with the value of 5
maintains its value.