Rust 编程语言内置的 Debug 特性非常方便,可以直接将任意类型的值以字符串的方式显示出来,而且还可以支持一定程度的格式化方式。在一般的情况下,要替我们自己的一个类型实作 Debug 特性,只需在其 derive 属性加上 Debug 参数就好了,没有什么难度。但是在比较特别的情况下,我们就无法用 derive 属性来实作 Debug 特性。

有关于 Rust 编程语言格式化文字的方式,可以参考《Rust 学习之路》系列文章的格式化文字章节。

以下是一个可以直接用 derive 属性来实作 Debug 特性的例子:

#[derive(Debug)]
struct MyStruct {
    f1: u8,
    f2: i16,
    f3: f64,
    f4: String,
}

如果我们再撰写以下程序:

let s = MyStruct {
    f1: 1,
    f2: 2,
    f3: 3.0,
    f4: "4".to_string()
};

println!("{s:05?}");
println!("{s:#05?}");

运行结果如下:

MyStruct { f1: 00001, f2: 00002, f3: 003.0, f4: "4" }
MyStruct {
    f1: 00001,
    f2: 00002,
    f3: 003.0,
    f4: "4",
}

但如果我们把类型为 Box<dyn Display> 的字段加进这个 MyStruct 结构体中的话,使用 #[derive(Debug)] 属性时就会无法编译。

use std::fmt::Display;

#[derive(Debug)]
struct MyStruct {
    f1: u8,
    f2: i16,
    f3: f64,
    f4: String,
    f5: Box<dyn Display>, // compilation error
}

这是因为 Box<dyn Display> 类型并没有去实作 Debug 特性,所以 #[derive(Debug)] 属性不知道要怎么去将 Box<dyn Display> 类型转成字符串。此时我们就要手动实作 Debug 特性了。

实作 Debug 特性的程序结构如下:

use std::fmt::{self, Debug, Formatter};

impl Debug for MyStruct {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        ...
    }
}

稍微介绍一下几个 Formatter 结构实体比较重要的方法:

  • alternate:判断在格式化字符串的时候是否有使用井字号 #,例如 {:#?}。通常这个井字号 # 用在 Debug 特性时,表示要让输出的文字变得更整齐。
  • width:取得格式化字符串的时候设置的文字宽度,例如 {:5?}。
  • align:取得格式化字符串的时候设置的文字对齐方式,例如 {:<5?}。
  • precision:取得格式化字符串的时候设置的数值精准度,例如 {:<5.2?}。
  • fill:取得格式化字符串的时候设置的填充字符,例如 {:@>5?}。
  • pad:可以传入一个字符串切片,并且可以根据 width、precision、fill 的信息对其做「填充」(padding)的动作。
  • sign_plus:取得格式化字符串的时候是否有使用正号 +,例如 {:+?}。
  • sign_minus:取得格式化字符串的时候是否有使用负号 -,例如 {:-?}。
  • sign_aware_zero_pad:取得格式化字符串的时候是否要用 0 来填充,例如 {:05?}。

如何?有没有觉得很复杂?如果我们试着自行简单实作 Debug 特性,可以写出如下的程序:

use std::fmt::{self, Debug, Formatter};

impl Debug for MyStruct {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.write_fmt(format_args!("MyStruct {{ f1: {:?}, f2: {:?}, f3: {:?}, f4: {:?}, f5: {} }}", self.f1, self.f2, self.f3, self.f4, self.f5.to_string()))
    }
}

当然,如果只是这样实作的话,就没有使用 #[derive(Debug)] 属性来实作 Debug 特性那样,拥有强大的格式化功能。例如以下程序,

let s = MyStruct {
    f1: 1,
    f2: 2,
    f3: 3.0,
    f4: "4".to_string(),
    f5: Box::new("5")
};

println!("{:05?}", s);
println!("{:#05?}", s);

运行结果如下:

MyStruct { f1: 1, f2: 2, f3: 3.0, f4: "4", f5: 5 }
MyStruct { f1: 1, f2: 2, f3: 3.0, f4: "4", f5: 5 }

如果要让类型的字段也可以拥有原先的格式化功能的话,可以考虑改用 Formatter 结构实体提供的 debug_* 方法来实作 Debug 特性。我们可以将 Debug 特性的程序实作改写如下:

use std::fmt::{self, Debug, Formatter};

impl Debug for MyStruct {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        let mut builder = f.debug_struct("MyStruct");

        builder.field("f1", &self.f1);
        builder.field("f2", &self.f2);
        builder.field("f3", &self.f3);
        builder.field("f4", &self.f4);
        builder.field("f5", &self.f5.to_string());

        builder.finish()
    }
}

然后再运行以下程序看看:

let s = MyStruct {
    f1: 1,
    f2: 2,
    f3: 3.0,
    f4: "4".to_string(),
    f5: Box::new("5")
};

println!("{:05?}", s);
println!("{:#05?}", s);

运行结果如下:

MyStruct { f1: 00001, f2: 00002, f3: 003.0, f4: "4", f5: "5" }
MyStruct {
    f1: 00001,
    f2: 00002,
    f3: 003.0,
    f4: "4",
    f5: "5",
}

这样虽然能让实作出来的 Debug 特性有格式化的功能,但 f5 的那个字段就直接被当作字符串,加上双引号 "" 处理了,然而我们原本并不想要这样。若要去掉双引号,就还得再替 f5 字段创建一个类型来包裹字符串,并替这个新类型实作 Debug 特性,使其不会在格式化时加上双引号,再把字符串用新类型包裹后的结果丢给 Formatter 结构实体提供的 debug_* 方法创建出来的 builder 来使用。似乎愈来愈麻烦了,事实上,我们可以使用以下介绍的套件来用一进程式叙述搞定所有的问题。

Debug Helper

「Debug Helper」是笔者开发的套件,提供了声明式宏,可以替结构体、元组结构体(tuple struct)、枚举等复合类型快速实作出 Debug 特性。

Crates.io

Cargo.toml

debug-helper = "*"

使用方法

一开始要先引用 debug_helper 这个 crate 下的宏。

对于含有名称字段的结构体,可以使用 impl_debug_for_struct! 宏来实作 Debug 特性。例如上面的例子,可以用 impl_debug_for_struct! 宏改写如下:

use std::fmt::Display;

struct MyStruct {
    f1: u8,
    f2: i16,
    f3: f64,
    f4: String,
    f5: Box<dyn Display>,
}

use std::fmt::{Debug, Formatter, Result as FormatResult};

impl Debug for MyStruct {
    fn fmt(&self, f: &mut Formatter<'_>) -> FormatResult {
        debug_helper::impl_debug_for_struct!(MyStruct, f, self, .f1, .f2, .f3, .f4, (.f5, "{}", self.f5))
    }
}

fn main() {
    let s = MyStruct {
        f1: 1, f2: 2, f3: 3.0, f4: "4".to_string(), f5: Box::new("5")
    };

    println!("{s:05?}");
    println!("{s:#05?}");
}

运行结果如下:

MyStruct { f1: 00001, f2: 00002, f3: 003.0, f4: "4", f5: 5 }
MyStruct {
    f1: 00001,
    f2: 00002,
    f3: 003.0,
    f4: "4",
    f5: 5,
}

如果是要对元组结构体实作 Debug 特性,可以使用 impl_debug_for_tuple_struct! 宏,程序如下:

#[macro_use]
extern crate debug_helper;

use std::fmt::{self, Formatter, Debug};

pub struct A(pub u8, pub i16, pub f64);

impl Debug for A {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
        impl_debug_for_tuple_struct!(A, f, self, .0, (.2, "{:.3}", self.2));
    }
}

let a = A(1, 2, std::f64::consts::PI);

println!("{:#?}", a);

/*
    A(
        1,
        3.142,
    )
*/

如果是要对枚举实作 Debug 特性,可以使用 impl_debug_for_enum! 宏,程序如下:

#[macro_use]
extern crate debug_helper;

use std::fmt::{self, Formatter, Debug};

pub enum A {
    V1,
    V2(u8, i16, f64),
    V3 {
        f1: u8,
        f2: i16,
        f3: f64,
    },
}

impl Debug for A {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
        impl_debug_for_enum!(A::{V1, (V2(f1, _, f3): (.f1, (.f3, "{:.3}", f3))), {V3{f1, f2: _, f3}: (.f1, (.f3, "{:.3}", f3))}}, f, self);
    }
}

let a = A::V1;
let b = A::V2(1, 2, std::f64::consts::PI);
let c = A::V3{
    f1: 1,
    f2: 2,
    f3: std::f64::consts::PI,
};

println!("{:#?}", a);
println!("{:#?}", b);
println!("{:#?}", c);

/*
    V1
    V2(
        1,
        3.142,
    )
    V3 {
        f1: 1,
        f3: 3.142,
    }
*/

如果想要增加原本不存在的字段,程序如下:

#[macro_use]
extern crate debug_helper;

use std::fmt::{self, Formatter, Debug};

pub struct A {
    pub f1: u8,
    pub f2: i16,
    pub f3: f64,
}

impl Debug for A {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
        impl_debug_for_struct!(A, f, self, .f1, (.f3, "{:.3}", self.f3), (.sum, "{:.3}", self.f1 as f64 + self.f2 as f64 + self.f3));
    }
}

let a = A {
    f1: 1,
    f2: 2,
    f3: std::f64::consts::PI,
};

println!("{:#?}", a);

/*
    A {
        f1: 1,
        f3: 3.142,
        sum: 6.142,
    }
*/
#[macro_use]
extern crate debug_helper;

use std::fmt::{self, Formatter, Debug};

pub struct A(pub u8, pub i16, pub f64);

impl Debug for A {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
        impl_debug_for_tuple_struct!(A, f, self, .0, (.2, "{:.3}", self.2), (.3, "{:.3}", self.0 as f64 + self.1 as f64 + self.2));
    }
}

let a = A(1, 2, std::f64::consts::PI);

println!("{:#?}", a);

/*
    A(
        1,
        3.142,
        6.142,
    )
*/

将元组结构体格式化成一般结构体:

#[macro_use]
extern crate debug_helper;

use std::fmt::{self, Formatter, Debug};

pub struct A(pub u8, pub i16, pub f64);

impl Debug for A {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
        impl_debug_for_struct!(A, f, self, let .f1 = self.0, let .f2 = self.1, let .f3 = self.2);
    }
}

let a = A(1, 2, std::f64::consts::PI);

println!("{:#?}", a);

/*
    A {
        f1: 1,
        f2: 2,
        f3: 3.141592653589793,
    }
*/

将一般结构体格式化成元组结构体:

#[macro_use]
extern crate debug_helper;

use std::fmt::{self, Formatter, Debug};

pub struct A {
    pub f1: u8,
    pub f2: i16,
    pub f3: f64,
}

impl Debug for A {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
        impl_debug_for_tuple_struct!(A, f, self, let .0 = self.f1, let .1 = self.f2, let .2 = self.f3);
    }
}

let a = A {
    f1: 1,
    f2: 2,
    f3: std::f64::consts::PI,
};

println!("{:#?}", a);

/*
    A(
        1,
        2,
        3.141592653589793,
    )
*/