gpt4 book ai didi

rust - 有没有一种方法可以在不直接实现 Debug 特性的情况下自定义 Debug 输出?

转载 作者:行者123 更新时间:2023-11-29 07:58:06 25 4
gpt4 key购买 nike

考虑以下代码:

#[derive(Debug)]
struct Test {
int: u8,
bits: u8,
hex: u8
}

fn main() {
let t = Test {
int: 1,
bits: 2,
hex: 3
};
println!("{:#?}", t);
}

运行时输出如下:

Test {
int: 1,
bits: 2,
hex: 3
}

很酷,我们可以毫不费力地转储结构,但我的一些数据结构包含位掩码或其他不易以 10 为基数读取的数据。对于位字段,读取它会容易得多,它们是输出类似 0b00000010 .

有没有一种简单的方法来获得这样的输出,而无需实现 Debug直接在结构上的特征(在另一种类型上的 Debug 特征会很好)?

Test {
int: 1,
bits: 0b00000010,
hex: 0x03
}

如果必须的话,我可以使用不同的类型,但我希望保持结构本身的调试特性像 #[derive(Debug)] 一样简单。 .

最佳答案

Is there a simple way to get output like this, without implementing the Debug trait directly on the struct (a Debug trait on another type would be fine)

是的。 #[derive(Debug)] 通过依次调用每个成员的 Debug::debug 来实现 Debug。按照 How to implement a custom 'fmt::Debug' trait? 中的说明进行操作对于您的新型包装器:

use std::fmt;

#[derive(Debug)]
struct Test {
int: u8,
bits: Bits,
hex: u8,
}

struct Bits(u8);

impl fmt::Debug for Bits {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "0b{:08b}", self.0)
}
}

在不同的方向,在你的主结构上有一个方法返回另一个“用于显示目的”的结构,类似于 std::path::Display 并不奇怪.这允许您将复杂的显示逻辑移动到一个单独的类型,同时允许您的原始结构没有可能妨碍您的新类型:

use std::fmt;

#[derive(Debug)]
struct Test {
int: u8,
bits: u8,
hex: u8,
}

impl Test {
fn pretty_debug(&self) -> PrettyDebug<'_> {
PrettyDebug {
int: &self.int,
bits: Bits(&self.bits),
hex: &self.hex,
}
}
}

#[derive(Debug)]
struct PrettyDebug<'a> {
int: &'a u8,
bits: Bits<'a>,
hex: &'a u8,
}

struct Bits<'a>(&'a u8);

impl fmt::Debug for Bits<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "0b{:08b}", self.0)
}
}

引用 u8 有点傻,但引用是这里最通用的解决方案 — 选择适合您的情况的数据类型。

您还可以直接为您的 PrettyDebug 类型实现 Debug:

use std::fmt;

#[derive(Debug)]
struct Test {
int: u8,
bits: u8,
hex: u8,
}

impl Test {
fn pretty_debug(&self) -> PrettyDebug<'_> {
PrettyDebug(self)
}
}

struct PrettyDebug<'a>(&'a Test);

impl fmt::Debug for PrettyDebug<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Test")
.field("int", &self.0.int)
.field("bits", &format_args!("0b{:08b}", self.0.bits))
.field("hex", &format_args!("0x{:02x}", self.0.hex))
.finish()
}
}

关于rust - 有没有一种方法可以在不直接实现 Debug 特性的情况下自定义 Debug 输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46749679/

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