Debug

デバッグ用途の「文字列への書き込み」トレイト。

導出可能: ✅

// Copyright 2025 Google LLC
// SPDX-License-Identifier: Apache-2.0

#[derive(Debug)]
pub struct Date {
    day: u8,
    month: u8,
    year: i64,
}

#[derive(Debug)]
pub struct User {
    name: String,
    date_of_birth: Date,
}

pub struct PlainTextPassword {
    password: String,
    hint: String,
}

impl std::fmt::Debug for PlainTextPassword {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PlainTextPassword")
            .field("hint", &self.hint)
            .field("password", &"[omitted]")
            .finish()
    }
}

fn main() {
    let user = User {
        name: "Alice".to_string(),
        date_of_birth: Date { day: 31, month: 10, year: 2002 },
    };

    println!("{user:?}");
    println!(
        "{:?}",
        PlainTextPassword {
            password: "Password123".to_string(),
            hint: "Used it for years".to_string()
        }
    );
}
  • 単純な「文字列への書き込み」機能を提供します。

  • 開発中にプログラマー向けの_デバッグ情報_を整形するためのものであり、 見た目やシリアライズのためのものではありません。

  • 文字列フォーマットマクロで {:?}{#?} の補間を使用できます。

  • derive/実装を行うべきでないケース: 構造体が機微なデータを保持している場合は、 その型に Debug を実装すべきか検討してください。

    • Debug が必要な場合は、derive するのではなく Debug を手動で実装することを 検討してください。実装から機微なデータを除外してください。