In Rust, variables are immutable by default, which means that their values cannot be changed. If a new value is assigned to a variable that was declared with the let
keyword, the program won’t compile:
fn main() {let a = 10; // 'a' is an immutable variablea = 5; // Cannot change the value of 'a'}
This feature of Rust is handy when the programmer knows that a variable being declared is not supposed to change throughout its lifetime.
When a variable does need to change its value during run-time, the mut
keyword can be used to indicate that the variable is mutable:
fn main() {let mut a = 10; // 'a' is a mutable variableprintln!("a = {}", a);a = 5; // Value of 'a' can now be changedprintln!("a = {}", a);}
There are certain instances where an immutable variable may need to transform its value temporarily and then become immutable again. This is known as shadowing.
fn main() {let a = 10; // 'a' is an immutable variable// The first 'a' is shadowed by this new one:let a = a * a;// 'a' is still immutableprintln!("a = {}", a);}
Shadowing also allows us to change the variable’s type (e.g., from string to integer) and its value:
fn main() {let string = "123"; // 'string' is an immutable variablelet string = string.len();println!("string length = {}", string);}
Free Resources