From 7e28f3ec8423c26005fe71bd09b1cdfc89c532a3 Mon Sep 17 00:00:00 2001 From: Colin Date: Tue, 22 Feb 2022 11:43:51 +0800 Subject: [PATCH] add a note about iterating an array The following snippet can run without an error: ```rust let mut a = [ 0, 1, 2, 3, 4 ]; let mut ind = 0; for num in a { println!("{}", num); if ind+1 < a.len() { a[ind+1] *= 10; } ind += 1; } println!("{:?}", a); ``` --- contents/basic/flow-control.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/contents/basic/flow-control.md b/contents/basic/flow-control.md index f997876c..c3db6e56 100644 --- a/contents/basic/flow-control.md +++ b/contents/basic/flow-control.md @@ -102,13 +102,16 @@ for 元素 in 集合 { ``` 这个语法跟 JavaScript 还蛮像,应该挺好理解。 -注意,使用 `for` 时我们往往使用集合的引用形式,除非你不想在后面的代码中继续使用该集合(比如我们这里使用了 `container` 的引用)。如果不使用引用的话,所有权会被转移到 `for` 语句块中,后面就无法再使用这个集合了): +注意,使用 `for` 时我们往往使用集合的引用形式,除非你不想在后面的代码中继续使用该集合(比如我们这里使用了 `container` 的引用)。如果不使用引用的话,所有权会被转移(move)到 `for` 语句块中,后面就无法再使用这个集合了): ```rust for item in &container { // ... } ``` +【注:相比集合(collection),对于实现了 `copy` 特征的数组(array)而言, `for item in arr` 并不会把 `arr` 转移,因此循环之后仍然可以使用 `arr` 。】 + + 如果想在循环中,**修改该元素**,可以使用 `mut` 关键字: ```rust for item in &mut collection {