为什么打印指针与打印取消引用的指针打印的内容相同? [英] Why does printing a pointer print the same thing as printing the dereferenced pointer?
问题描述
来自 Rust 指南:
From the Rust guide:
要取消引用(获取被引用的值而不是引用本身)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 通常关注对象值(即内容中有趣的部分)而不是对象标识(内存地址).Display
for &T
其中 T
实现 Display
直接遵循内容.为 Display
的 String
实现手动扩展该宏:
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屋!