First time I am encountering a typed language allowing to declare a variable name twice in the same scope. Wouldn't there be a chance to override an existing variable by mistake? What advantage does it bring?
1 Answers
There is a chapter in the book about this.
Shadowing is different from marking a variable as mut, because we’ll get a compile-time error if we accidentally try to reassign to this variable without using the let keyword. By using let, we can perform a few transformations on a value but have the variable be immutable after those transformations have been completed.
The other difference between mut and shadowing is that because we’re effectively creating a new variable when we use the let keyword again, we can change the type of the value but reuse the same name. For example, say our program asks a user to show how many spaces they want between some text by inputting space characters, but we really want to store that input as a number
let spaces = " "; // String
let spaces = spaces.len(); // number
In short, it allows you to "modify" a value, in a way that is technically immutable. Rust ensures that you cannot use the shadowed variable, so it's perfectly typesafe.
I'm no Rust expert, but from a language design perspective it's an interesting thing to encourage. But I think the point is to discourage the use of mutable values whenever possible by allowing you to immutably override a name with a new type and value.

- 1
- 1

- 178,991
- 47
- 309
- 337
-
I wouldn't say it modifies, since it creates a completely new variable and will delete both the new and old one once the scope finishes. Shadowing is done compile-time, so no dynamic casting or modifying occurs. https://stackoverflow.com/a/48227487/7652095 – Ali Deym Jun 20 '20 at 01:05
-
1Agreed, which is why I put “modified” in quotes. It implies the new value at least depends on the old value, but is in fact a new immutable value. – Alex Wayne Jun 20 '20 at 01:18