1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-05-16 07:36:05 +02:00

Replace one of the examples of the aliasing rule

This commit is contained in:
Nicole LeGare 2025-04-17 16:48:01 -07:00
parent 5211436446
commit 097b700bc3

View File

@ -17,21 +17,36 @@ fn main() {
}
```
Similarly, consider the case of iterator invalidation:
We can also look at a case where these rules prevent incorrect optimizations:
```rust,editable,compile_fail
fn sum_and_zero(a: &mut i32, b: &mut i32) {
*a = *a + *b;
*b = 0;
}
fn main() {
let mut vec = vec![1, 2, 3, 4, 5];
for elem in &vec {
vec.push(elem * 2);
}
let mut x = 5;
sum_and_zero(&mut x, &mut x);
}
```
<details>
- In both of these cases, modifying the collection by pushing new elements into
- In the first case, modifying the collection by pushing new elements into
it can potentially invalidate existing references to the collection's elements
if the collection has to reallocate.
- In the second case, the aliasing rule prevents mis-compilation: The output of
`sum_and_zero` depends on the ordering of the two operations, which means if
the compiler swaps the order of these operations (which it's allowed to do) it
changes the result.
- The equivalent code in C exhibits undefined behavior, which may result in
mis-compilation and unexpected behavior, even if it doesn't cause a crash.
- Rust's aliasing rules provide strong guarantees about how references can
alias, allowing the compiler to apply optimizations without breaking the
semantics of your program.
</details>