Trait core::fmt::Debug1.0.0[][src]

#[lang = "debug_trait"]
pub trait Debug { fn fmt(&self, f: &mut Formatter) -> Result; }

? 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 ).

Examples

Deriving an implementation:

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

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

println!("The origin is: {:?}", origin);Run

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 {
        write!(f, "Point {{ x: {}, y: {} }}", self.x, self.y)
    }
}

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

println!("The origin is: {:?}", origin);Run

This outputs:

The origin is: Point { x: 0, y: 0 }

There are a number of debug_* methods on Formatter to help you with manual implementations, such as debug_struct.

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 };

println!("The origin is: {:#?}", origin);Run

This outputs:

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 {
        write!(f, "({:?}, {:?})", self.longitude, self.latitude)
    }
}

assert_eq!("(1.987, 2.983)".to_owned(),
           format!("{:?}", Position { longitude: 1.987, latitude: 2.983, }));Run

Implementors