Skip to content

Formatting traits

The type suffix at the end of a replacement field selects a formatting trait. A custom type can support any representation by implementing the corresponding trait.

Syntax Trait Typical use
{} Display user-facing text
{:?} Debug programmer-facing inspection
{:x?} / {:X?} Debug Debug with integer fields in lower / upper hex
{:b} Binary base 2 integers
{:o} Octal base 8 integers
{:x} LowerHex lower-case hexadecimal
{:X} UpperHex upper-case hexadecimal
{:p} Pointer pointer address
{:e} LowerExp lower-case exponent notation
{:E} UpperExp upper-case exponent notation

Deriving Debug does not implement Display. Display asks the type author to choose one user-facing representation, and Rust intentionally does not provide a derive for that decision.

EXAMPLE: CI-CHECKEDTEST ASSERTED · examples/format-output/src/reference_examples.rs#custom-display
pub struct Coordinate(pub i32, pub i32);

impl fmt::Display for Coordinate {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "({}, {})", self.0, self.1)
    }
}

Open the interactive cheat sheet to compare common specifications by output.