rust - 没有 "let"的阴影

标签 rust shadowing

<分区>

据我了解,Rust 中的阴影允许您通过使用 let 并重新声明变量来使用相同的变量,例如

let x = 5;

let x = x + 1;

let x = x * 2;

println!("The value of x is: {}", x);

但是,如果您使变量可变,那么它不会模拟阴影,例如:

let mut x = 5;
println!("The value of x is: {}", x);
x = 6;
println!("The value of x is: {}", x);
 x = 7;
println!("The value of x is: {}", x);

例子1&2中,变量存储在什么地方,是栈还是堆?

最佳答案

示例中的所有值都存储在堆栈中。在示例 1 中,每个 let 语句都会将一个新值压入堆栈。

看起来你从 The Rust Programming Language 得到了例子.也许再读一遍这一段以强调:

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.

关于rust - 没有 "let"的阴影,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54066883/

相关文章:

Rust MemWriter 返回指向 Buffer 的指针

json - 如何在写入文件之前删除文件的内容?

macros - 我可以用我自己的自定义宏覆盖标准库中的宏吗?

Scala 方法中变量名不明确

javascript - 带有阴影的奇怪行为

opengl - Piston 中的 InvalidEnum 错误

rust - Rust 中的下划线 : "consider using"

c++ - Make -Wshadow 忽略初始化列表

java - 为什么两种情况下的输出不同?

python - 错误 : "Cannot find reference to loads in json.py"