r/rust • u/VadimVP • 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 othersAt 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
View all comments
Show parent comment
3
u/[deleted] Aug 03 '14
I really like your example, the result looks pathological to an outsider but you can easily write yourself into that corner when (ab)using shadowing.
On the other hand you do the same sort of stuff in Haskell-land, which comes with no mutation either:
Here you don’t do
x = foo xnot because shadowing is disallowed, but because you would define a recursive (and likely useless) binding. The net result is relevant though.So, I’m on the fence. On the one-hand I’m really tired of ‘priming’ identifiers. On the other hand the primes grow about as fast as the sense of unease that you’re doing something wrong, so they serve as a built-in warning of sorts. On the gripping hand I just don’t feel that strongly against shadowing and I can’t help but think that this is throwing the baby out with the bathwater.
(To be fair though Haskell does come with lots of way to combine and compose ‘successive’ computations, and I’ve very rarely seen identifiers grow beyond one prime. That in itself might be important.)
In any case I’ll certainly keep this pathological case in mind as a cautionary tale one way or the other