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

Debug

Усі типи, які хочуть використовувати форматувальні traits з std::fmt, потребують реалізації, щоб їх можна було виводити. Автоматичні реалізації надаються лише для типів, таких як у бібліотеці std. Усі інші мають бути реалізовані вручну якимось способом.

trait fmt::Debug робить це дуже простим. Усі типи можуть derive (автоматично створити) реалізацію fmt::Debug. Це не так для fmt::Display, який має бути реалізований вручну.

#![allow(unused)]
fn main() {
// This structure cannot be printed either with `fmt::Display` or
// with `fmt::Debug`.
struct UnPrintable(i32);

// The `derive` attribute automatically creates the implementation
// required to make this `struct` printable with `fmt::Debug`.
#[derive(Debug)]
struct DebugPrintable(i32);
}

Усі типи бібліотеки std також автоматично можна виводити за допомогою {:?}:

// Derive the `fmt::Debug` implementation for `Structure`. `Structure`
// is a structure which contains a single `i32`.
#[derive(Debug)]
struct Structure(i32);

// Put a `Structure` inside of the structure `Deep`. Make it printable
// also.
#[derive(Debug)]
struct Deep(Structure);

fn main() {
    // Printing with `{:?}` is similar to with `{}`.
    println!("{:?} months in a year.", 12);
    println!("{1:?} {0:?} is the {actor:?} name.",
             "Slater",
             "Christian",
             actor="actor's");

    // `Structure` is printable!
    println!("Now {:?} will print!", Structure(3));

    // The problem with `derive` is there is no control over how
    // the results look. What if I want this to just show a `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 };

    // Pretty print
    println!("{:#?}", peter);
}

Можна вручну реалізувати fmt::Display, щоб керувати відображенням.

Дивіться також:

attributes, derive, std::fmt, та struct