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

标签 pointers rust dereference

来自 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对于 &T,其中 T 实现 Display 直接延迟到内容。为 DisplayString 实现手动扩展该宏:

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

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

如果你关心对象标识/内存地址,你可以使用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

关于pointers - 为什么打印指针与打印取消引用的指针打印相同的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35206251/

相关文章:

rust - 为什么通过 DerefMut 可变借用闭包不起作用?

c - 带有数组指针的for循环,将值设置为指针

c++ - 在头文件中将变量声明为指针和非指针的区别

rust - 通过 HashMap::Entry 进行模式匹配时出现 "ambiguous associated type"错误(错误代码 E0223)

json - 使用 serde_json 将内部枚举值从 &str 反序列化为 u64

generics - 使用泛型取消引用强制

c - 反转字符串是段错误

C - 如何使用指向结构的指针复制结构

rust - 有没有办法获得 i32 的 u32 绝对值,它对 std::i32::MIN 做正确的事情?

c - 在堆栈上查找函数的根