Variables and Mutability
Variable
In rust, variables are defined using the let
keyword.
let x = 5;
By default
, all variable in Rust are immutable
, which means once a value is bounded to a variable, you can not change the variable to hold a difference value. For instance, the following code will leads to error:
let x = 5;
x = 10; // this will throw an error.
However, Rust allows you to create mutable variable
by using the mut
keyword.
let mut y = 5;
y = 10;
Constants
Like immutable variables, constants are values that are bound to a name and are not allowed to change. Also, you aren’t allowed to use mut
with constants.
Here's an example:
const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3;
Shadowing
You can declare a new variable with the same name as a previous variable. That said, the first variable is shadowed by the second, which means that the second variable is what the compiler will see when you use the name of the variable.
fn main() {
let x = 5;
let x = x + 1;
{
let x = x + 2;
println!("The value of x in the inner scope is: {x}");
}
println!("The value of x in the outer scope is: {x}");
}
shadowing
and mut
?
Shadowing can change variable type after shadowing.
mut
can not change it's type after reassigning it's value. For example:
let mut spaces = " ";
spaces = spaces.len();
error[E0308]: mismatched types
--> value.rs:16:14
|
15 | let mut spaces = " ";
| ----- expected due to this value
16 | spaces = spaces.len();
| ^^^^^^^^^^^^ expected &str
, found usize
|
help: try removing the method call
|
16 - spaces = spaces.len();
16 + spaces = spaces;
|