You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: content/en/docs/c2.borrowing.md
+9-10Lines changed: 9 additions & 10 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -196,19 +196,17 @@ fn main() {
196
196
// 💯 Using the `move` keyword forces the closure to take ownership: `let greet = move || println!("Hello, {name}!");`
197
197
```
198
198
199
-
Using an index `[n]` on collections like `Vec` or `HashMap`involves an implicit shared borrow of the element. Example: The compiler effectively converts `a[0]` into `*a.index(0)`.
199
+
Accessing an element from a slice or collection like `Vec` or `HashMap`for read-only access involves the [`Index` trait](https://doc.rust-lang.org/std/ops/trait.Index.html). The compiler implicitly converts `a[0]` into `*a.index(0)`, which involves an implicite shared borrow of the collection.
200
200
201
201
```rust
202
-
fnmain() {
203
-
leta=vec![1, 2, 3]; // Vector of a Copy type
204
-
letb=vec!["Apple".to_string(), "Pear".to_string()]; // Vector of a non-Copy/ move type
205
-
206
-
// 💡 a[0] and b[0] are references to the relevant elements of the vectors
202
+
// Two concepts in the example: 1. Implicite shared reference; 2. Assigning Copy types/ non-Copy types to a new variable.
207
203
208
-
letc=a[0]; // A copy of a[0] is assigned to `c: i32`
// ⭐️ Each reference is scoped to the function call.
269
268
// 👨🏫 Try remove `.clone()`. The borrow checker will not let it compile.
270
269
// 💥 cannot move out of `p.name` which is behind a shared reference
271
270
```
@@ -325,7 +324,7 @@ fn main() {
325
324
}
326
325
```
327
326
328
-
Using an index `[n]` on collections like `Vec`or `HashMap` to modify an element involves an implicit mutable borrow. Example: The compiler effectively converts `a[0]` into `*a.index_mut(0)`.
327
+
Accessing an element from a slice or collection like `Vec`for mutable access involves the [`IndexMut` trait](https://doc.rust-lang.org/std/ops/trait.IndexMut.html). The compiler implicitly converts `a[0]` into `*a.index_mut(0)`, which involves an implicit mutable borrow of the collection.
0 commit comments