You've already forked comprehensive-rust
mirror of
https://github.com/google/comprehensive-rust.git
synced 2025-07-14 18:14:29 +02:00
Clarify the "Slices" question and fix the answer (#990)
Clarify the question and fix the answer
This commit is contained in:
@ -8,12 +8,13 @@ fn main() {
|
|||||||
println!("a: {a:?}");
|
println!("a: {a:?}");
|
||||||
|
|
||||||
let s: &[i32] = &a[2..4];
|
let s: &[i32] = &a[2..4];
|
||||||
|
|
||||||
println!("s: {s:?}");
|
println!("s: {s:?}");
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
* Slices borrow data from the sliced type.
|
* Slices borrow data from the sliced type.
|
||||||
* Question: What happens if you modify `a[3]`?
|
* Question: What happens if you modify `a[3]` right before printing `s`?
|
||||||
|
|
||||||
<details>
|
<details>
|
||||||
|
|
||||||
@ -30,7 +31,6 @@ fn main() {
|
|||||||
* Slices always borrow from another object. In this example, `a` has to remain 'alive' (in scope) for at least as long as our slice.
|
* Slices always borrow from another object. In this example, `a` has to remain 'alive' (in scope) for at least as long as our slice.
|
||||||
|
|
||||||
* The question about modifying `a[3]` can spark an interesting discussion, but the answer is that for memory safety reasons
|
* The question about modifying `a[3]` can spark an interesting discussion, but the answer is that for memory safety reasons
|
||||||
you cannot do it through `a` after you created a slice, but you can read the data from both `a` and `s` safely.
|
you cannot do it through `a` at this point in the execution, but you can read the data from both `a` and `s` safely.
|
||||||
More details will be explained in the borrow checker section.
|
It works before you created the slice, and again after the `println`, when the slice is no longer used. More details will be explained in the borrow checker section.
|
||||||
|
|
||||||
</details>
|
</details>
|
||||||
|
Reference in New Issue
Block a user