Why does printing a pointer print the same thing as printing the dereferenced pointer?

Rust usually focuses on object value (i.e. the interesting part of the contents) rather than object identity (memory addresses). The implementation of Display for &T where T implements Display defers directly to the contents. Expanding that macro manually for the String implementation of Display:

impl<'a> Display for &'a String {
    fn fmt(&self, f: &mut Formatter) -> Result {
        Display::fmt(&**self, f)
    }
}

That is, it is just printing its contents directly.

If you care about object identity/the memory address, you can use the Pointer formatter, {:p}:

fn main() {
    let x = 1;
    let ptr_y = &x;
    println!("x: {}, ptr_y: {}, address: {:p}", x, ptr_y, ptr_y);
}

Output:

x: 1, ptr_y: 1, address: 0x7fff4eda6a24

playground

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)