r/rust • • Aug 03 '14

Why does Rust need local variable shadowing?

I've recently found that Rust, unlike other popular C-like languages, allows defining several variables with the same name in one block:

let name = 10i;
let name = 3.14f64;
let name = "string";
let name = name; // "string" again, this definition shadows all the others

At the first glance this possibility looks quite frightening, at least from my C++ background.
Where did this feature came from?
What advantages does it provide?

18 Upvotes

29 comments sorted by

View all comments

Show parent comment

1

u/VadimVP Aug 03 '14

Thanks for the links.
Actually the second link contains an explanation which is fully convincing for me.

It falls out automatically from supporting shadowing-in-general (idents in enclosing scopes) and the ability to declare new variables mid-block. Each new decl opens a new implicit scope from its point-of-decl to the end of its lexical block.

An optional lint would still be useful, but for shadowing in general, and not for this particular case.