Rust formatting traits - Display, Debug, hex, binary, and more
The type suffix at the end of a Rust replacement field selects a formatting trait. {} uses Display, {:?} uses Debug, {:x} uses LowerHex, {:b} uses Binary, and the remaining suffixes map to their corresponding std::fmt traits.
| 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 |
Display is not automatic
Section titled “Display is not automatic”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.
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)
}
}For the complete method signature and a focused explanation of Formatter, write!, and .to_string(), see implement Display for a Rust struct.
Related references
Section titled “Related references”- Debug vs Display for choosing between user-facing and programmer-facing output
- Implement Display for writing a custom
{}representation - Number bases and exponent formatting for numeric trait suffixes
- Exact format specifier grammar for the order of flags and type suffixes
Open the interactive cheat sheet to compare common specifications by output.