Back to course

Variables, Mutability & Constants

Rust for Systems & Web3 Security

Variables in Rust

By default, variables in Rust are immutable. This is a safety feature.

rust let x = 5; // Immutable // x = 6; // This would cause a compiler error!

To make a variable mutable, use the mut keyword:

rust let mut y = 10; y = 11; // This works

Constants

Constants are always immutable and must have a type annotation. They can be declared in any scope, including the global scope.

rust const MAX_POINTS: u32 = 100_000;

Shadowing

Rust allows you to 'shadow' a variable by redeclaring it with let. This is useful for changing the type of a variable while keeping the same name.