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

本小妞迷上赌 提交于 2019-12-17 07:43:32

问题


From the Rust guide:

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

So I did it:

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

This gives me the same results (x=1; y=1) even without an explicit dereference:

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

Why? Shouldn't ptr_y print the memory address and *ptr_y print 1? Is there some kind of auto-dereference or did I miss something?


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/27852613/why-does-printing-a-pointer-print-the-same-thing-as-printing-the-dereferenced-po

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!