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


Scope

Global Variables

Rust does not allow global variables. There are two options however for declaring a value in the global context:

  1. constants (i.e. const THRESHOLD: i32 = 10)

  2. static variables

A static variable is simply a variable that's given the 'static reference lifetime-it is kept for the entire lifecycle. Additionally, a static variable can only be declared with constant functions (i.e. declared with const fn) so that they can be computed at compile time.


Unsafe


CategoryRicottone

Rust/ScopeAndMutability (last edited 2021-09-02 00:46:23 by DominicRicottone)