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 appear similar, they serve different purposes in different contexts. We will discuss these distinctions 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
}

In this example, // starts a single-line comment, causing the rest of the line to be ignored by the compiler.

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}");
}

The {x} inside println! is a placeholder replaced with the value of x at runtime. This is Rust’s string interpolation syntax, which allows variables to be embedded directly in the string.

Alternatively, you can pass the value of x as a separate argument:

println!("x is now {}", x);

Both forms produce the same output for plain variables. However, to print expressions like x + 1, only the second form is allowed.

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