Rustlers Atom 1.4 - Variables, binding, shadowing, mutability
On this page
<figure class="video" style="margin:0;">
<div style="position:relative;width:100%;padding-bottom:56.25%;height:0;overflow:hidden;">
<iframe src="https://www.youtube.com/embed/FFFLZVFyodI?si=OrV3sVrVbeDksnto"
title="YouTube video player"
style="position:absolute;top:0;left:0;width:100%;height:100%;border:0;"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
referrerpolicy="strict-origin-when-cross-origin"
allowfullscreen></iframe>
</div>
</figure>
Rust variables are bindings: a name tied to a value. By default, they are immutable.
Immutable vs mutable#
fn main() {
let x = 5;
// x = 6; ❌ compile error
let mut y = 5;
y = 6; // ✅ works
println!("y = {}", y);
}The mut keyword makes intent explicit. No silent mutation is allowed in rust.
Shadowing#
Instead of mutating, you can re-declare the same name.
fn main() {
let spaces = " ";
let spaces = spaces.len(); // new binding, new type
println!("spaces = {}", spaces);Every let creates a new binding, and the old one is gone. Bindings live inside their scope. Shadowing can narrow scope deliberately.
Constants#
Use const for compile-time values.
const MAX_SCORE: u32 = 100;
fn main() {
println!("MAX_SCORE = {}", MAX_SCORE);
}Constants require an explicit type and are always immutable. Following best practices, constants should be named using upper snake case.