Should get an error about not being mutable

I have this code:

pub fn run(){
    let name = "Calvin";
    let age = 48;
    
    let age = 49;
    println!("My name is {} and today is my birthday and I am now {}", name, age);
}

It runs fine without any errors but should it not give me an error about age not being mutable? Aren't variables immutable by default?

That is called shadowing, the first variable named age and the second variable named age are actually not the same one.
The second assignment would be a mutation if it didn't start with the let keyword.

This would be an attempt to mutate age:

pub fn run(){
    let name = "Calvin";
    let age = 48; // mut is required for this to compile
    
    age = 49;
    println!("My name is {} and today is my birthday and I am now {}", name, age);
}

Related: What is the usage of variable shadowing

3 Likes

Thank you very much clear explanation

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.