2.4 Variables and Mutability

Rust declares variables using the let keyword:

let variable_name: OptionalType = OptionalValue;
  • By default, variables are immutable.
  • Rust prevents the use of uninitialized variables, requiring an assignment before use.

While constants and immutable variables may seem similar, they serve distinct purposes in different contexts. A detailed discussion of their differences will be provided in later chapters.

2.4.1 Immutable by Default

Rust uses immutable variables by default to enhance safety, predictability, and performance.

fn main() {
    let x: i32 = 5;
    // x = 6; // Error: cannot assign to an immutable variable
}

2.4.2 Making Variables Mutable

Use mut if you need to change a variable's value:

fn main() {
    let mut x = 5;
    x = 6;
    println!("x is now {x}");
}

2.4.3 Comparison with C

In C, variables are mutable by default. The const keyword can be used to declare immutable variables:

int x = 5;
x = 6; // Allowed

const int y = 5;
// y = 6; // Error: assignment of read-only variable