Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

デバッグ

std::fmt のフォーマット用 traits を使いたいすべての型は、出力可能にするための実装を必要とします。自動実装は、std ライブラリ内の型などに対してのみ提供されます。それ以外の型はすべて、何らかの方法で手動実装されていなければなりません。

fmt::Debug trait は、これを非常に簡単にします。すべての 型は fmt::Debug の実装を derive(自動生成)できます。これは、手動で実装しなければならない fmt::Display には当てはまりません。

#![allow(unused)]
fn main() {
// この構造体は `fmt::Display` でも `fmt::Debug` でも
// 出力できません。
struct UnPrintable(i32);

// `derive` 属性は、この `struct` を `fmt::Debug` で出力可能にするために
// 必要な実装を自動的に作成します。
#[derive(Debug)]
struct DebugPrintable(i32);
}

すべての std ライブラリの型も、{:?} で自動的に出力可能です。

// `Structure` に対して `fmt::Debug` の実装を導出します。`Structure` は
// 単一の `i32` を含む構造体です。
#[derive(Debug)]
struct Structure(i32);

// `Structure` を構造体 `Deep` の中に入れます。これも出力可能に
// します。
#[derive(Debug)]
struct Deep(Structure);

fn main() {
    // `{:?}` による出力は `{}` による出力と似ています。
    println!("{:?} months in a year.", 12);
    println!("{1:?} {0:?} is the {actor:?} name.",
             "Slater",
             "Christian",
             actor="actor's");

    // `Structure` は出力可能です!
    println!("Now {:?} will print!", Structure(3));

    // `derive` の問題は、結果の見た目を制御できないことです。
    // これを単に `7` と表示したい場合はどうすればよいでしょうか?
    println!("Now {:?} will print!", Deep(Structure(7)));
}

つまり、fmt::Debug は確かにこれを出力可能にしますが、多少の優雅さを犠牲にします。Rust は {:#?} による「プリティプリント」も提供しています。

#[derive(Debug)]
struct Person<'a> {
    name: &'a str,
    age: u8
}

fn main() {
    let name = "Peter";
    let age = 27;
    let peter = Person { name, age };

    // プリティプリント
    println!("{:#?}", peter);
}

表示を制御するために fmt::Display を手動で実装できます。

関連項目:

attributesderivestd::fmt、 および struct