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)
Syntax
impl fmt::Display for T { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result }
Parameters
| Parameter | Description |
|---|---|
write!(f, ...) |
Write formatted output. |
f.alternate() / f.precision() |
Respect {:#} and {:.N}. |
to_string() |
Provided automatically. |
Examples
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.
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.
Related
#[derive]· Generate standard trait implementations such as Debug, Clone, PartialEq, Eq, Hash, Default and PartialOrd for your types.From and Into· Convert between types: implement From<T> and get Into for free; ? uses From to convert error types.- Rust Traits · tutorial