Rust Scope and Mutability

Variables in Rust are available only in their immediate context. Most are also immutable. These defaults can be relaxed with keywords.


Mutability

Many variables are actually constant in Rust. To enable reassignment of a variable, it must be declared with the mut keyword.

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

Shadowing

It is possible to shadow a variable, so as to allow re-use of a common name.

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


Unsafe


CategoryRicottone