From 097b700bc3a3cedcd6576527377666d6a6a151d7 Mon Sep 17 00:00:00 2001 From: Nicole LeGare Date: Thu, 17 Apr 2025 16:48:01 -0700 Subject: [PATCH] Replace one of the examples of the aliasing rule --- src/borrowing/examples.md | 27 +++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/src/borrowing/examples.md b/src/borrowing/examples.md index b90ba647..cb3ad36b 100644 --- a/src/borrowing/examples.md +++ b/src/borrowing/examples.md @@ -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); } ```
-- 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. +