Skip to content

Commit f42d51b

Browse files
committed
feat(rust): Add content about shadowing in variable
1 parent 7b10d79 commit f42d51b

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

docs/languages/rust/variable.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,23 @@ const c: i32 = 1; // 能够通过编译,但会被编译器警告,因为常
7272

7373
例如,定义数组要求数组的长度必须是常量表达式。但 C++ 中 `const` 声明的所谓“常量”并不一定能满足这点;而 C++ 中的 `constexpr` 与 Rust 中的 `const` 则都能满足。
7474

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+
7592
## 变量类型
7693

7794
### 基本类型

0 commit comments

Comments
 (0)