1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-03-18 05:37:52 +02:00

Clarify the "Slices" question and fix the answer (#990)

Clarify the question and fix the answer
This commit is contained in:
Dominik Maier 2023-07-17 18:32:49 +02:00 committed by GitHub
parent faab0e2ee6
commit 9e825fbd59
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -8,12 +8,13 @@ fn main() {
println!("a: {a:?}");
let s: &[i32] = &a[2..4];
println!("s: {s:?}");
}
```
* 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>
@ -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.
* 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.
More details will be explained in the borrow checker section.
you cannot do it through `a` at this point in the execution, but you can read the data from both `a` and `s` safely.
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>