Check whether a mutable reference points to a particular object

Is there a way of checking whether r points to x or y in the following?

Would much prefer a non-unsafe way of doing so, but based on my limited knowledge of aliasing, even the unsafe ways are unsound.

let mut x = 2;
let mut y = 2;
let r = if unimplemented!() { &mut x } else { &mut y };
// add a check here

Edit: I'm asking with the constraint that code may only be executed after the 3 lines of code shown above.

This seems to work, and doesn't use unsafe:

let mut x = 2;
let mut y = 2;

let x_addr = std::ptr::addr_of!(x);
let y_addr = std::ptr::addr_of!(y);

let r = if use_x { &mut x } else { &mut y };

(
    std::ptr::eq(r, x_addr),
    std::ptr::eq(r, y_addr),
)

Well, I would consider this cheating since you edited in the middle of the given code rather than the place where it says "add a check here".

Once you've created the mutable reference, you can no longer access the variable in any way. It's impossible to make this check without first storing the address of each variable before creating the mutable reference.

4 Likes