If immutable variables can used with shadow and get their value changed then what is the reason behind having it as a separate type to declare variables?

Hello Team,

If my question is very basic, please dont mind.
I am trying to learn Rust.

Right now I am at data types where I came across let, const, which are interesting.

The part I didnt understand is, if by default all variables are immutable unless there is let mut, and those variables are can not be changed in general way but with shadow they can be changed then what is the reason behind having immutable behaviour ?

I mean

let x: u32 = 10; // immutable for now 
let x = 20 ; // not any more. 

let mut y: u32 = 20; //mutable 
y = 30; // no errors expected 

except an an extra let, I see x and y as are same things. What is the advantage of defining x as immutable at initial step ?

Please help me understand.

Thank you.
Raja Genupula

The reasoning is mostly to do with expressing your intent, I think - shadowing replaces a variable, mutation changes a variable.

One place this comes in handy is if you have a mutable variable and want it to become immutable later on:

let mut x = MyStruct::new();

x.mutate();

let x = x; // Subsequent code should not be able to mutate `x`,
           // so we rebind it.

Also, they have slightly different effects at runtime:

  • Shadowing creates a new variable, and renders the previous version inaccessible. However, the original variable still exists, and so the original value of x will not be dropped till the end of the scope.
  • Reassigning immediately drops the previous value.
4 Likes

Shadowing and mutation will have different effects when scoping is involved, just consider the following code:

let x = 0;

{
  let x = 1;
}

dbg!(x)

Vs

let mut x = 0;

{
  x = 1;
}

dbg!(x)

(I'm on mobile therefore some typos might be there)

Shadowing behaves mostly the same as any variables with different names, except for the scoping effect that the old/outer shadowed variable isn't accessible by name anymore.