Every variable and reference is immutable by default.
let
declares a variablelet mut
declares a mutable variableconst
declares a constant that gets inlined during compilationstatic
declares a variable with a static location in memorystatic mut
declares a mutable variable with a static location in memory
Variables declared using let
or let mut
:
fn main() {
let x: i32 = 5;
let mut y: i32 = 10;
y = 12;
}
Type can be inferred:
fn main() {
let x = -4; // i32
}
Initialization can be deferred, type annotation is optional:
fn main() {
let z;
// ...
z = 6;
}
Initializing the same variable multiple times shadows the previous declaration, types can differ:
fn main() {
let x = 5;
// ...
let x = "kek";
}
Static variables are declared using static
in the global scope. They can be
mutable, although mutable static variables is a bad practice because they're
not thread safe. They must have a type annotation.
Static variables have a static place in memory and can be passed around as references.
static NICKNAME: &str = "henchbruv";
static mut PLAYERS: u32 = 0; // :(
Constants are declared using const
and are values that are inlined during
compilation. They can be declared in any scope. They must have a type
annotation.
const MAX_VALUE: u32 = 1337;
Unless interior mutability or a static place in memory is required, constants are preferred over statics.