Print address of a ref in Rust?

Is there a way to print the 0x... address of a &T or &self in Rust ?

I'm running into debugging issues, and I'm wondering: these two things, which I thought were the same object in memory ... are they actually same object in memory ?

Via the “p” format specifier.. See here and here.

To make up an example:

fn main() {
    let x = 42;
    let y = 42;
    let (a, b, c, d, e, f) = (&x, &y, &x, &y, &42, &(40 + 2));

    println!("{a:p} {b:p} {c:p} {d:p} {e:p} {f:p}");

example output

0x7fffafe8ac60 0x7fffafe8ac64 0x7fffafe8ac60 0x7fffafe8ac64 0x55f8a282e000 0x55f8a282e000

Rust Playground

(the last two, e and f, showcase static promotion, and how the compiler can deduplicate equal constants)


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.