问题
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:
- hard to follow code (easier to create bugs)
- accessing variables when one intended to access a different variable (creates bugs)
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:
- What kind of advantages/disadvantages are there?
- What are the use cases for shadow variables?
- When not to use them in Rust?
- What do different people from different programming background have to keep in mind? (and which pitfalls not to fall into)
回答1:
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:
- RFC 459: Disallow type/lifetime parameter shadowing
- What does 'let x = x' do in Rust?
- Why do I need rebinding/shadowing when I can have mutable variable binding?
- In Rust, what's the difference between "shadowing" and "mutability"?
来源:https://stackoverflow.com/questions/59860476/what-is-the-rationale-behind-allowing-variable-shadowing-in-rust