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 ?
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.
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.