All Rust variables are immutable by default. The keyword mut must be used after let during assignment to create a mutable variable:
fn main() {
let mut number = 5;
println!("{}", number); // prints '5'
number = 10;
println!("{}", number); // prints '10'
}
The above example also contains some instances of
println!(), one of Rust's macros
(covered in more detail later). println!() prints the value of a given variable, depending on its data type.
Exercise:
Fix the problem with the code below (try running it first to see why it won't compile):
Using the keyword const, Rust variables can also be defined as constants, forcing complete immutability throughout the entire lifetime of a variable:
const FORTY_TWO: u8 = 20+12+10;
fn main() {
println!("{}", FORTY_TWO)
}
The piece of syntax involving the colon before the equals sign will be explained on the next page.
Constants can be defined at the very beginning of a Rust script, outside any functions (explained later), making them ideal for defining a value that has to be known and reused across a whole program.
To completely ensure that constants stay immutable, it is impossible for a constant to have a value that can't be calculated at compile-time.