Differences between revisions 1 and 4 (spanning 3 versions)
Revision 1 as of 2021-09-01 19:57:18
Size: 664
Comment:
Revision 4 as of 2025-10-15 16:15:23
Size: 975
Comment: Rewrite
Deletions are marked like this. Additions are marked like this.
Line 1: Line 1:
= Rust Scope and Mutability = = Rust Mutability =
Line 3: Line 3:
Variables in Rust are available only in their immediate context. Most are also immutable. These defaults can be relaxed with keywords. A description of '''mutability''' (and '''immutability''') in Rust.
Line 11: Line 11:
== Mutability == == Description ==
Line 13: Line 13:
Many variables are actually constant in Rust. To enable reassignment of a variable, it must be declared with the `mut` keyword. Most variables are actually immutable by default.

To ''enable'' mutability, a variable must be declared with the `mut` keyword.
Line 22: Line 24:


=== Shadowing ===

It is possible to shadow a variable, so as to allow re-use of a common name.
It ''is'' possible to '''shadow''' a variable name, however.
Line 39: Line 37:
== Unsafe == == 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);
}
}}}

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)