In Rust it is encouraged to shadow variables:
But wait, doesn’t the program already have a variable named guess? It does, but Rust allows us to shadow the previous value of guess with a new one.
Won't this feature just introduce problems like:
I have based this information from my own experience and the following sources: 1 2 3 4 5
What are the underlying reasons behind the decision to include variable shadowing?
It does have it advantages as to just create guess
and not guess_str
vs guess_int
. There are both advantages and disadvantages.
What convinced the inventors of Rust that the advantages are greater than the disadvantages?
The programming world seems divided about this; some languages only issue warnings and discourage shadowing, some languages disallow it explicitly, some allow it and others even encourage it. What is the reasoning?
If possible I'd like to understand more, and a complete answer would possibly include:
Because it was initially supported and never removed:
It’s more like we never forbade shadowing, since it just fell out of the implementation of the compiler.
As I recall, Graydon floated the idea of forbidding shadowing, but I stuck up for the feature, nobody else really cared, and so it stayed.
- pcwalton
See also: