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:
Shadowing also plays nicely with nested scopes in Rust. It makes the code even more readable and adds the possibility of “falling back” to the initial type/value of the shadowed variable.
Variable shadowing could be avoided by simply renaming variables with unambiguous names. We could rewrite the previous examples: The inner scope has access to variables defined in the outer scope.
In computer programming, variable shadowing occurs when a variable declared within a certain scope (decision block, method, or inner class) has the same name as a variable declared in an outer scope.
Shadowing of local variables should generally be avoided, as it can lead to inadvertent errors where the wrong variable is used or modified. Some compilers will issue a warning when a variable is shadowed.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With