gpt4 book ai didi

rust - 调试格式化程序是否使用取消引用?

转载 作者:行者123 更新时间:2023-12-03 11:29:41 25 4
gpt4 key购买 nike

我对 Debug 格式化程序如何到达引用链的末尾感到困惑。
我的理解是println!("{:?}", x)扩展为:

... print(&x) ...
x而不是移动/复制它。
现在打印 MyNumber(1)而不是预期的 &MyNumber(1) :
#[derive(Debug)]
struct MyNumber(u8);

fn main() {
let x = MyNumber(1);
println!("{:?}", x);
}
我假设调试格式化程序遵循通用 Deref Rust 语言本身为所有引用定义的实现 ( impl<T> Deref for &T)。
如果是这样,那么为什么下面的代码会打印 MyNumber(1)而不仅仅是 1 ?
use std::ops::{Deref};

#[derive(Debug)]
struct MyNumber(u8);

impl Deref for MyNumber {
type Target = u8;

fn deref(&self) -> &Self::Target {
&self.0
}
}

fn main() {
let x = MyNumber(1);
println!("{:?}", x);
}
在我看来,调试格式化程序遵循 Deref实现于 &T Rust 语言本身,但忽略了 Deref在我的自定义类型上实现。
有谁知道为什么会这样?非常感谢任何帮助!

最佳答案

Does anyone know why this happens? Any help much appreciated!


如果您查看 the documentation for Debug然后搜索 you will find :
impl<'_, T> Debug for &'_ T where
T: Debug + ?Sized,
这意味着有一个专门针对委托(delegate)给底层对象的引用的批量实现。在您的情况下是 MyNumber ,此时这就是所使用的。 Deref 没有实现,相反,每种智能指针类型都有实现(如果您在页面中搜索,您会找到 BoxRc 的实现)。
所以你的代码打印 MyNumber(1)因为这就是它被告知要做的事情:它调用 DebugMyNumber 上实现.如果你想要不同的东西,你需要实现(而不是派生) Debug委托(delegate)给它的底层类型。

关于rust - 调试格式化程序是否使用取消引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64388681/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com