Mutability: When Rust Plays Hard to Get
In Rust, variables are immutable by default. That means once you assign a value, it's set in stone—unless you specifically ask Rust for permission to change it. This is like Rust saying, "I care about your safety!"
1. Immutable Variables
By default, variables in Rust cannot be changed after they're assigned.
fn main() {
let name = "Rustacean";
name = "Crab Coder"; // ERROR: Cannot assign twice to immutable variable
println!("Hello, {}!", name);
}
Boom! Rust yells at you. But don’t worry, it’s just looking out for you.
2. Making Variables Mutable
If you really need to modify a variable, you can use mut
:
fn main() {
let mut age = 25;
age += 1;
println!("Happy Birthday! You are now {} years old!", age);
}
Now Rust is happy, and so is your ever-growing age!
Constants: The VIP of Rust
Unlike variables, constants are always immutable and must have their type explicitly declared. Also, they follow SCREAMING_SNAKE_CASE by convention.
1. Declaring a Constant
const PI: f64 = 3.14159;
fn main() {
println!("The value of PI is {}", PI);
}
Unlike let
, constants are always immutable, and they must be assigned a constant expression (not a computed value at runtime!).
2. Why Use Constants?
- They cannot be changed after compilation.
- They exist globally throughout the program.
- They make your code more readable and efficient.
3. Differences Between const
and let
Feature | const |
let |
---|---|---|
Mutability | Always immutable | Mutable with mut |
Type | Must be explicitly declared | Can be inferred |
Scope | Accessible anywhere | Scoped where declared |
Computation | Only compile-time values | Can use runtime expressions |
Example of what not to do:
fn main() {
const ERROR: i32 = some_function(); // ERROR: Constants require a constant value
}
fn some_function() -> i32 {
42
}
Wrapping Up
Rust loves safety, and that’s why variables are immutable by default. If you want to change a value, use mut
. If you need a true constant, use const
. Now go forth and write safer, cleaner Rust code!
0 Comments