Day 2 of Reading "The Rust Book" Cover to Cover: Variables, Shadowing & Constants

Quick summary of what I learnt in chapter 2:

Variables in Rust are immutable by default.

fn main() {
let x = 5;
// x = 6; // ❌ Won't compile
}

Trying to assign a new value to x will result in a compile-time error because Rust doesn't allow you to modify immutable variables. If you actually want to change a variable, you need to declare it as mutable.

let mut x = 5;x = 6;

Shadowing

Rust lets you declare a new variable with the same name as an existing one. This is called shadowing.

fn main() {
let x = 5;
let x = x + 1;
{
let x = x * 2;
println!("The value of x in the inner scope is: {x}");
}
println!("The value of x is: {x}");
}
Output:
The value of x in the inner scope is: 12
The value of x is: 6

Each let x = ... creates an entirely new variable instead of modifying the previous one.

The inner x only exists inside that block. Once the block ends, Rust goes back to using the outer x.

Shadowing is not the same as mut

Shadowing looks similar to making a variable mutable, but they’re actually different.

Even after shadowing, the new variable is still immutable.

fn main() {
let x = 5;
let x = x + 1;
// x = 10; // ❌ Won't compile
}

The second let creates a brand-new variable. It doesn’t make x mutable.

Advantage of shadowing

You can change the type of a variable while keeping the same name.

let spaces = "   ";
let spaces = spaces.len();

In the first line, spaces is a string.

In the second line, spaces becomes a number representing the string's length.

This doesn't work with the mutable variables, because the type has to stay the same.

let mut spaces = "   ";
spaces = spaces.len(); // ❌ Type mismatch

Constants

Rust also has constants, which are declared using the const keyword instead of let.

A few things to remember:

  • Constants are always immutable.
  • Their type must be specified.
  • They can be declared in any scope, including the global scope.
  • They can only be assigned a constant expression — not something calculated at runtime.
  • By convention, constant names are written in UPPER_SNAKE_CASE.

Example:

const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3;

Unlike regular variables, constants remain valid for the entire lifetime of the program within the scope where they’re defined.

Final thoughts

On to Day 3.

0 comments:

Post a Comment