pub trait Debug {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>;
}
Expand description

? formatting.

Debug should format the output in a programmer-facing, debugging context.

Generally speaking, you should just derive a Debug implementation.

When used with the alternate format specifier #?, the output is pretty-printed.

For more information on formatters, see the module-level documentation.

This trait can be used with #[derive] if all fields implement Debug. When derived for structs, it will use the name of the struct, then {, then a comma-separated list of each field’s name and Debug value, then }. For enums, it will use the name of the variant and, if applicable, (, then the Debug values of the fields, then ).

Stability

Derived Debug formats are not stable, and so may change with future Rust versions. Additionally, Debug implementations of types provided by the standard library (libstd, libcore, liballoc, etc.) are not stable, and may also change with future Rust versions.

Examples

Deriving an implementation:

#[derive(Debug)]
struct Point {
    x: i32,
    y: i32,
}

let origin = Point { x: 0, y: 0 };

assert_eq!(format!("The origin is: {:?}", origin), "The origin is: Point { x: 0, y: 0 }");

Manually implementing:

use std::fmt;

struct Point {
    x: i32,
    y: i32,
}

impl fmt::Debug for Point {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Point")
         .field("x", &self.x)
         .field("y", &self.y)
         .finish()
    }
}

let origin = Point { x: 0, y: 0 };

assert_eq!(format!("The origin is: {:?}", origin), "The origin is: Point { x: 0, y: 0 }");

There are a number of helper methods on the Formatter struct to help you with manual implementations, such as debug_struct.

Types that do not wish to use the standard suite of debug representations provided by the Formatter trait (debug_struct, debug_tuple, debut_list, debug_set, debug_map) can do something totally custom by manually writing an arbitrary representation to the Formatter.

impl fmt::Debug for Point {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Point [{} {}]", self.x, self.y)
    }
}

Debug implementations using either derive or the debug builder API on Formatter support pretty-printing using the alternate flag: {:#?}.

Pretty-printing with #?:

#[derive(Debug)]
struct Point {
    x: i32,
    y: i32,
}

let origin = Point { x: 0, y: 0 };

assert_eq!(format!("The origin is: {:#?}", origin),
"The origin is: Point {
    x: 0,
    y: 0,
}");

Required methods

Formats the value using the given formatter.

Examples
use std::fmt;

struct Position {
    longitude: f32,
    latitude: f32,
}

impl fmt::Debug for Position {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("")
         .field(&self.longitude)
         .field(&self.latitude)
         .finish()
    }
}

let position = Position { longitude: 1.987, latitude: 2.983 };
assert_eq!(format!("{:?}", position), "(1.987, 2.983)");

assert_eq!(format!("{:#?}", position), "(
    1.987,
    2.983,
)");

Trait Implementations

Perform the conversion.

Implementations on Foreign Types

Format the program and arguments of a Command for display. Any non-utf8 data is lossily converted using the utf8 replacement character.

Shows the original regular expression.

Shows the original regular expression.

Styles have a special Debug implementation that only shows the fields that are set. Fields that haven’t been touched aren’t included in the output.

This behaviour gets bypassed when using the alternate formatting mode format!("{:#?}").

use ansi_term::Colour::{Red, Blue};
assert_eq!("Style { fg(Red), on(Blue), bold, italic }",
           format!("{:?}", Red.on(Blue).bold().italic()));

The Debug output of the ISO week w is the same as d.format("%G-W%V") where d is any NaiveDate value in that week.

Example

use chrono::{NaiveDate, Datelike};

assert_eq!(format!("{:?}", NaiveDate::from_ymd(2015,  9,  5).iso_week()), "2015-W36");
assert_eq!(format!("{:?}", NaiveDate::from_ymd(   0,  1,  3).iso_week()), "0000-W01");
assert_eq!(format!("{:?}", NaiveDate::from_ymd(9999, 12, 31).iso_week()), "9999-W52");

ISO 8601 requires an explicit sign for years before 1 BCE or after 9999 CE.

assert_eq!(format!("{:?}", NaiveDate::from_ymd(    0,  1,  2).iso_week()),  "-0001-W52");
assert_eq!(format!("{:?}", NaiveDate::from_ymd(10000, 12, 31).iso_week()), "+10000-W52");

The Debug output of the naive time t is the same as t.format("%H:%M:%S%.f").

The string printed can be readily parsed via the parse method on str.

It should be noted that, for leap seconds not on the minute boundary, it may print a representation not distinguishable from non-leap seconds. This doesn’t matter in practice, since such leap seconds never happened. (By the time of the first leap second on 1972-06-30, every time zone offset around the world has standardized to the 5-minute alignment.)

Example

use chrono::NaiveTime;

assert_eq!(format!("{:?}", NaiveTime::from_hms(23, 56, 4)),              "23:56:04");
assert_eq!(format!("{:?}", NaiveTime::from_hms_milli(23, 56, 4, 12)),    "23:56:04.012");
assert_eq!(format!("{:?}", NaiveTime::from_hms_micro(23, 56, 4, 1234)),  "23:56:04.001234");
assert_eq!(format!("{:?}", NaiveTime::from_hms_nano(23, 56, 4, 123456)), "23:56:04.000123456");

Leap seconds may also be used.

assert_eq!(format!("{:?}", NaiveTime::from_hms_milli(6, 59, 59, 1_500)), "06:59:60.500");

The Debug output of the naive date d is the same as d.format("%Y-%m-%d").

The string printed can be readily parsed via the parse method on str.

Example

use chrono::NaiveDate;

assert_eq!(format!("{:?}", NaiveDate::from_ymd(2015,  9,  5)), "2015-09-05");
assert_eq!(format!("{:?}", NaiveDate::from_ymd(   0,  1,  1)), "0000-01-01");
assert_eq!(format!("{:?}", NaiveDate::from_ymd(9999, 12, 31)), "9999-12-31");

ISO 8601 requires an explicit sign for years before 1 BCE or after 9999 CE.

assert_eq!(format!("{:?}", NaiveDate::from_ymd(   -1,  1,  1)),  "-0001-01-01");
assert_eq!(format!("{:?}", NaiveDate::from_ymd(10000, 12, 31)), "+10000-12-31");

The Debug output of the naive date and time dt is the same as dt.format("%Y-%m-%dT%H:%M:%S%.f").

The string printed can be readily parsed via the parse method on str.

It should be noted that, for leap seconds not on the minute boundary, it may print a representation not distinguishable from non-leap seconds. This doesn’t matter in practice, since such leap seconds never happened. (By the time of the first leap second on 1972-06-30, every time zone offset around the world has standardized to the 5-minute alignment.)

Example

use chrono::NaiveDate;

let dt = NaiveDate::from_ymd(2016, 11, 15).and_hms(7, 39, 24);
assert_eq!(format!("{:?}", dt), "2016-11-15T07:39:24");

Leap seconds may also be used.

let dt = NaiveDate::from_ymd(2015, 6, 30).and_hms_milli(23, 59, 59, 1_500);
assert_eq!(format!("{:?}", dt), "2015-06-30T23:59:60.500");
source

impl Debug for Entry

Implementors