Rust Mutability
A description of mutability (and immutability) in Rust.
Contents
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:
declare a string literal (i.e. const THRESHOLD: i32 = 10)
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);
}