Explain with examples
When two pointers or references point to the same location in memory (or to overlapping locations), we say that they alias each other.
For example:
let x = 5;
let a = &x;
let b = &x;
dbg!(a, b); // a and b point to the same value
3 Likes
Rust pays attention to aliasing, because it causes subtle odd behaviors:
fn foo(a: &mut i32, b: &i32) {
if b == 1 {
*a = 2;
// Can a write to a have changed b too?
// Rust says no, but in languages with mutable aliasing it could be yes
assert_eq!(b, 1);
}
}
let mut x = 1;
// makes both arguments of `foo` share the same value
foo(&mut x, &x); // not allowed in Rust, but allowed in C/C++
5 Likes
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.