Rust 1.99 (2024 edition) reference · Traits and Smart Pointers

Rust impl Display Type

Implement std::fmt::Display to control how a type prints with {} and converts with to_string().

Rust 1.99 (2024 edition)

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

impl fmt::Display for T { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result }

Parameters

ParameterDescription
write!(f, ...) Write formatted output.
f.alternate() / f.precision() Respect {:#} and {:.N}.
to_string() Provided automatically.

Examples

Example 1
use std::fmt;

struct Money(i64);

impl fmt::Display for Money {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "${}.{:02}", self.0 / 100, self.0 % 100)
    }
}

fn main() {
    let price = Money(1999);
    println!("price: {price}");
    let label = price.to_string() + " incl. VAT";
    println!("{label}");
}

Output

price: $19.99
$19.99 incl. VAT

Run this on your computer — see “Get Started” for setup.

Display for an enum
use std::fmt;

enum Status { Active, Suspended }

impl fmt::Display for Status {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let s = match self { Status::Active => "active", Status::Suspended => "suspended" };
        f.write_str(s)
    }
}

fn main() {
    println!("[{:>10}]", Status::Active.to_string());
    println!("{}", Status::Suspended);
}

Output

[    active]
suspended

Run this on your computer — see “Get Started” for setup.

Was this page helpful?