2.3 Variables and Mutability
2.3.1 Immutable by Default
In Rust, variables are immutable by default, enhancing safety by preventing unintended changes.
Rust Example:
fn main() { let x = 5; // x = 6; // Error: cannot assign twice to immutable variable }
To make a variable mutable, use the mut
keyword.
fn main() { let mut x = 5; x = 6; // Allowed println!("The value of x is: {}", x); }
2.3.2 Comparison with C
In C, variables are mutable by default.
int x = 5;
x = 6; // Allowed
To make a variable constant in C, you use the const
keyword.
const int x = 5;
// x = 6; // Error: assignment of read-only variable ‘x’