📝 Variables in Rust: Simple, Safe, and Powerful
What are variables?
Variables let you store and work with data in your programs. In Rust, they’re safe, fast, and a little different from what you might know!
✨ Declaring Variables
rust
Loading…
let
creates a variable (immutable by default)mut
makes it mutable (you can change it)- You can add a type (like
f64
) if you want
🔄 Changing Values (Mutability)
rust
Loading…
Tip: If you forget mut
, Rust will give you a friendly error!
🕵️ Shadowing: Reuse Names, Change Types
rust
Loading…
- Shadowing lets you reuse a variable name
- You can even change its type!
🧠 Best Practices
- Prefer immutability (
let
) unless you need to change the value - Use clear, descriptive names
- Shadowing is great for transformations
- Type annotations are optional, but can help with clarity
🦀 Pro Tip: Rust’s compiler is your friend. If you make a mistake, it’ll tell you exactly what’s wrong (and how to fix it)!