为什么打印指针与打印取消引用的指针一样打印? [英] Why does printing a pointer print the same thing as printing the dereferenced pointer?

查看:76
本文介绍了为什么打印指针与打印取消引用的指针一样打印?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自Rust指南:

要取消引用(获取要引用的值而不是引用本身)y,我们使用星号(*)

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):

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);
}

为什么? ptr_y不应该打印内存地址,而*ptr_y不应该打印1吗?是否存在某种类型的自动取消引用,或者我错过了某些事情?

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?

推荐答案

Rust通常关注对象值(即内容的有趣部分),而不是对象标识(内存地址). 用于&T,其中T实现Display直接顺应内容.手动扩展该宏以实现DisplayString:

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.

如果您关心对象标识/内存地址,则可以使用 Pointer格式程序{:p}:

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);
}

输出:

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

游乐场

这篇关于为什么打印指针与打印取消引用的指针一样打印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆