在 Rust 中允许变量阴影背后的基本原理是什么?

What is the rationale behind allowing variable shadowing in Rust?

在 Rust 中 encouraged 隐藏变量:

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.

此功能不会引入以下问题:

我根据自己的经验和以下来源得出这些信息:1 2 4 5

决定包含变量阴影的根本原因是什么?

guess_int 相比,它确实具有仅创建 guess 而不是 guess_str 的优势。有优点也有缺点。

是什么让 Rust 的发明者相信优点大于缺点?

编程界似乎对此存在分歧;有些语言只发出警告并阻止隐藏,有些语言明确禁止,有些允许,有些甚至鼓励。这是什么道理?

如果可能我想了解更多,完整的答案可能包括:

因为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

另请参阅: