← 中文资源

简体中文版本

Debug 交替标志输出 pretty 形态

手写 Debug 时用 f.alternate() 区分两种形态:{:?} 输出紧凑单行,{:#?} 输出带缩进的多行 pretty 版本;两个开关走同一个 impl,不引入额外依赖。

阅读英文原文

运行说明

一个 Debug impl 通过 f.alternate() 服务两种形态。紧凑的 {:?} 单行打印 Config { name: “api”, retries: 5 }——日志与单行报错要的形状。

交替的 {:#?} 走另一分支,打印带缩进的多行 pretty 形态——name 与 retries 各占一行。两次调用走同一个 impl,差别只有那个标志位。

要点提示

  • alternate() 只在 {:#?} 形式下为 true。
  • pretty 输出自带换行与缩进。

核心语句

if f.alternate() {

代码示例

use std::fmt;

struct Config {
    name: String,
    retries: u32,
}

// hand-written Debug: the alternate flag is true for {:#?}, which prints the pretty multi-line shape
impl fmt::Debug for Config {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if f.alternate() {
            write!(
                f,
                "Config {{\n    name: {:?},\n    retries: {},\n}}",
                self.name, self.retries
            )
        } else {
            write!(f, "Config {{ name: {:?}, retries: {} }}", self.name, self.retries)
        }
    }
}

fn main() {
    let config = Config { name: String::from("api"), retries: 5 };

    println!("{config:?}");
    println!("{config:#?}");
}