We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
shadowing
variable
1 parent 7b10d79 commit f42d51bCopy full SHA for f42d51b
docs/languages/rust/variable.md
@@ -72,6 +72,23 @@ const c: i32 = 1; // 能够通过编译,但会被编译器警告,因为常
72
73
例如,定义数组要求数组的长度必须是常量表达式。但 C++ 中 `const` 声明的所谓“常量”并不一定能满足这点;而 C++ 中的 `constexpr` 与 Rust 中的 `const` 则都能满足。
74
75
+### 变量遮蔽
76
+
77
+其英文为 `shadowing`,可被译为“遮蔽”、“重影”,是 Rust 的一种特殊语法,允许在同一作用域中声明一个与之前变量同名的新变量,从而遮蔽之前的变量。
78
79
+这相当于把变量名绑定到了一个新的值上,而不是修改了原来的值。这种特性在一些场景下很有用,可以减少变量的数量、减轻给变量取名字的负担。
80
81
+```rust
82
+let spaces = " "; // spaces 是一个字符串
83
+let spaces = spaces.len(); // spaces 变成了一个数字
84
85
+let mut spaces = " "; // spaces 是一个字符串
86
+// spaces = spaces.len(); // 编译无法通过,因为 spaces 已经是一个字符串,不能再赋值为数字,类型不匹配
87
88
+let mut num = 1;
89
+num *= 2; // OK
90
+```
91
92
## 变量类型
93
94
### 基本类型
0 commit comments