为什么打印指针与打印取消引用的指针打印相同的内容?

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

来自 Rust 指南:

To dereference (get the value being referred to rather than the reference itself) y, we use the asterisk (*)

所以我做到了:

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

这给了我相同的结果 (x=1; y=1) 即使没有显式取消引用:

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

为什么?不应该 ptr_y 打印内存地址和 *ptr_y 打印 1 吗?是否有某种自动取消引用或我错过了什么?

Rust 通常关注对象值(即内容中有趣的部分)而不是对象标识(内存地址)。 implementation of Display for &T where T implements Display directly defer to the contents.为 Display:

String 实现手动扩展该宏
impl<'a> Display for &'a String {
    fn fmt(&self, f: &mut Formatter) -> Result {
        Display::fmt(&**self, f)
    }
}

也就是说,它只是直接打印它的内容。

如果你关心对象identity/the内存地址,你可以使用Pointer formatter, {:p}:

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

输出:

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

playground

fn main() {
 let x = &42;
 let address = format!("{:p}", x); // this produces something like '0x7f06092ac6d0'
 println!("{}", address);
}