Rust Syntax & Basic Constructs
Estimated reading: 3 minutes 28 views

🦀 Rust – Variables: Declare, Mutate, and Shadow Like a Pro

🧲 Introduction – Why Learn Variables in Rust?

Variables are the foundation of any programming language—but Rust adds powerful rules around immutability, type safety, and memory ownership. Understanding how variables work in Rust is key to writing safe and efficient code.

🎯 In this guide, you’ll learn:

  • How to declare variables using let, mut, and const
  • The difference between mutable and immutable bindings
  • How variable shadowing works
  • Best practices for naming and using variables in Rust

🧾 Declare Variables in Rust

fn main() {
    let language = "Rust"; // Immutable
    let mut version = 2025; // Mutable
    const PI: f32 = 3.14;   // Constant

    println!("{} v{}", language, version);
}

🔍 Explanation:

  • let → Immutable variable by default
  • mut → Allows mutation (must be declared explicitly)
  • const → Fixed value with explicit type, declared in UPPERCASE

🔄 Mutability in Action

fn main() {
    let mut score = 90;
    println!("Score: {}", score);

    score = 95; // ✅ allowed because it's mutable
    println!("Updated Score: {}", score);
}

📌 Trying to mutate an immutable variable will cause a compile-time error:

fn main() {
    let level = 1;
    level = 2; // ❌ error: cannot assign twice to immutable variable
}

🎭 Shadowing: Re-Declare to Transform

Rust allows shadowing—declaring a new variable with the same name:

fn main() {
    let name = "Rust";
    let name = name.len(); // shadows previous `name`
    println!("Length: {}", name);
}

📌 Key Benefits of Shadowing:

  • Transform values without using mut
  • Keeps previous binding immutable
  • Can even change types

Example with type change:

fn main() {
    let spaces = "   ";
    let spaces = spaces.len(); // From &str → usize
    println!("Spaces count: {}", spaces);
}

🧠 Constants (const) vs. Immutables (let)

Featurelet (Immutable)const
MutabilityImmutable (by default)Always immutable
TypeInferredMust be explicitly typed
ScopeLocal to blockGlobal or scoped
Namingsnake_caseUPPER_SNAKE_CASE

Example:

const MAX_USERS: u32 = 1000;

🛠️ Type Inference vs. Explicit Typing

Rust can infer types:

let year = 2025; // inferred as i32

Or you can declare explicitly:

let year: u16 = 2025;

🧪 Types inferred must be consistent with operations used.


⚠️ Common Variable Mistakes

MistakeError DescriptionFix
Reassigning immutable variable“cannot assign twice to immutable variable”Use mut if reassignment is needed
Declaring const without type“missing type for const item”Always specify type for const
Changing type with mutNot allowed (mutable ≠ flexible types)Use shadowing instead

📌 Summary – Recap & Next Steps

Rust enforces safety by default through immutability, explicit mutation, and shadowing, giving developers fine control over how variables behave.

🔍 Key Takeaways:

  • Variables are immutable by default with let
  • Use mut for values that need to change
  • const values must include types and use uppercase naming
  • Shadowing allows safe transformation without mutation

⚙️ Up next: Explore Rust – Constants to understand how constants differ from variables and when to use them.


❓FAQs


Why are Rust variables immutable by default?
✅ To encourage safe programming practices and reduce side effects. You must explicitly choose to make a variable mutable.


What is shadowing in Rust?
✅ Shadowing lets you re-declare a variable with the same name, even with a different type. Unlike mut, shadowing doesn’t mutate—it rebinds.


Is mut the same as shadowing?
✅ No. mut allows changes to the same variable, while shadowing creates a new variable with the same name.


Can I use const inside functions?
✅ No. const declarations must be at the global or module level. Use let or static in functions instead.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Rust – Variables

Or Copy Link

CONTENTS
Scroll to Top