Rust Mutability

A description of mutability (and immutability) in Rust.


Description

Most variables are actually immutable by default.

To enable mutability, a variable must be declared with the mut keyword.

fn main() {
    let mut x = 0;
    x = 1;
}

It is possible to shadow a variable name, however.

fn main() {
    let spaces = "   ";
    let spaces = spaces.len();
}


Tips

Global Scope

Rust does not allow variables in the global scope. To place a value there, try:

  1. declare a string literal (i.e. const THRESHOLD: i32 = 10)

  2. use a function that returns a value given the 'static reference lifetime

fn coerce_static<'a>(_: &'a i32) -> &'a i32 {
    &NUM
}

fn main() {
    let lifetime_num = 9;
    let coerced_static = coerce_static(&lifetime_num);
}


CategoryRicottone

Rust/Mutability (last edited 2025-10-15 16:15:23 by DominicRicottone)