Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Standard Library Modules

The std::fmt module

Reference for std::fmt: the formatting traits, Formatter methods and flags, debug_struct builders, Arguments, fmt::Write and the fmt::Error type.

std::fmt is the machinery behind println!, format!, write! and every {} placeholder. It defines the formatting traits (Display, Debug, LowerHex, Binary, ...), the Formatter that traits write into, helper builders for Debug output, the Arguments value produced by format_args!, and the Write trait for text sinks.

To make your own type printable you implement a formatting trait and write to the Formatter you are given. Width, fill, alignment and precision flags from the placeholder are available on that formatter.

Rust
use std::fmt;

struct Id(u32);
impl fmt::Display for Id {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "#{}", self.0)
    }
}

Try it

Rust Display, padding and Debug builders

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust fmt::Write, Arguments and errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

The formatting traits all share one method shape, fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result:

Trait Placeholder Typical use
Display {} User-facing text.
Debug {:?}, {:#?} Programmer-facing output; usually #[derive(Debug)].
LowerHex, UpperHex {:x}, {:X} Hexadecimal.
Binary, Octal {:b}, {:o} Base 2 and 8.
LowerExp, UpperExp {:e}, {:E} Scientific notation.
Pointer {:p} Addresses.

Important items:

Item Description
Formatter::write_str, write_fmt Write text or other formatted arguments.
Formatter::pad, pad_integral Write text honoring width, fill, alignment, precision and sign flags.
width(), precision(), fill(), alternate(), sign_plus() Read the flags of the current placeholder.
debug_struct, debug_tuple, debug_list, debug_map, debug_set Builders for derive-like Debug output that respect {:#?}.
fmt::Write Trait with write_str; implemented by String. Not the same as io::Write.
fmt::Arguments Precompiled format string and arguments, from format_args!.
fmt::Error Zero-sized error returned when writing fails.
fmt::format(args) Function behind format!.

Errors and edge cases: fmt::Result is Result<(), fmt::Error>. fmt::Error carries no information; implementations should return it only when the sink fails, never to signal a bad value. to_string() on a type whose Display returns Err panics.

Usage notes

  • Use f.pad(...) (or write! into a padded string) when you want {:>10} to work with your type. Plain write!(f, ...) ignores width and alignment.
  • Derived Debug is stable across runs but its layout is not a promise; do not parse it.
  • {:#?} pretty-prints through the same builders, so hand-written Debug with debug_struct gets it for free.
  • Implementing Display gives you ToString automatically through a blanket impl.
  • fmt::Write and io::Write both have write_fmt, so write! works on either; import only the one you need to avoid ambiguity.
  • format_args! avoids an allocation; use it in functions that take fmt::Arguments (logging, panics).
  • Width and precision can be passed at runtime: {:>width$} or {:.*}.