I'm confused as to why this code:
use std::ptr::{addr_of, addr_of_mut};
struct Pair {
x: u32,
y: u32,
}
fn main() {
let mut p = Pair { x: 1, y: 2 };
{
let p: *mut Pair = &mut p;
unsafe {
let get = || addr_of!((*p).x).read();
let y = addr_of_mut!((*p).y);
y.write(get());
}
}
println!("x={} y={}", p.x, p.y);
}
produces this error:
error[E0502]: cannot borrow `p.y` as mutable because it is also borrowed as immutable
--> src/main.rs:14:21
|
13 | let get = || addr_of!((*p).x).read();
| -- ------ first borrow occurs due to use of `p` in closure
| |
| immutable borrow occurs here
14 | let y = addr_of_mut!((*p).y);
| ^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
15 | y.write(get());
| --- immutable borrow later used here
|
= note: this error originates in the macro `addr_of_mut` (in Nightly builds, run with -Z macro-backtrace for more info)
I thought borrow checking did not happen with pointers. Can anyone explain what's going on here? Thanks!
Playground link: Rust Playground