为什么 Rust 允许在一个范围内两次声明相同的变量名? [英] Why Rust allows declaring same variable name twice in a scope?

查看:34
本文介绍了为什么 Rust 允许在一个范围内两次声明相同的变量名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我第一次遇到允许在同一范围内两次声明变量名称的类型化语言.不会有机会错误地覆盖现有变量吗?带来什么好处?

First time I am encountering a typed language allowing to declare a variable name twice in the same scope. Wouldn't there be a chance to override an existing variable by mistake? What advantage does it bring?

推荐答案

书中关于此的一章.

Shadowing 与将变量标记为 mut 不同,因为如果我们不小心尝试重新分配给这个变量而不使用 let 关键字,我们会得到一个编译时错误.通过使用 let,我们可以对一个值执行一些转换,但在这些转换完成后,变量是不可变的.

Shadowing is different from marking a variable as mut, because we’ll get a compile-time error if we accidentally try to reassign to this variable without using the let keyword. By using let, we can perform a few transformations on a value but have the variable be immutable after those transformations have been completed.

mut 和 shadowing 的另一个区别是,因为当我们再次使用 let 关键字时,我们有效地创建了一个新变量,所以我们可以更改值的类型但重用相同的名称.例如,假设我们的程序要求用户通过输入空格字符来显示他们想要在某些文本之间有多少空格,但我们真的想将该输入存储为数字

The other difference between mut and shadowing is that because we’re effectively creating a new variable when we use the let keyword again, we can change the type of the value but reuse the same name. For example, say our program asks a user to show how many spaces they want between some text by inputting space characters, but we really want to store that input as a number

let spaces = "   "; // String
let spaces = spaces.len(); // number

简而言之,它允许您修改"一个值,在技术上是不可变的.Rust 确保您不能使用 shadowed 变量,因此它是完全类型安全的.

In short, it allows you to "modify" a value, in a way that is technically immutable. Rust ensures that you cannot use the shadowed variable, so it's perfectly typesafe.

我不是 Rust 专家,但从语言设计的角度来看,这是值得鼓励的一件有趣的事情.但我认为关键是要阻止尽可能使用可变值,方法是允许您使用新类型和值不可变地覆盖名称.

I'm no Rust expert, but from a language design perspective it's an interesting thing to encourage. But I think the point is to discourage the use of mutable values whenever possible by allowing you to immutably override a name with a new type and value.

这篇关于为什么 Rust 允许在一个范围内两次声明相同的变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆