Implement Display With Width And Alignment

A custom Display impl formats fields with width, alignment, and zero padding through write!, so println! renders tidy rows directly.

RustCli Tooling

Code

rustsnippet
26 lines
use std::fmt;

struct Invoice {
    id: u32,
    cents: i64, // 非负分值
    paid: bool,
}

// Display:write! 用宽度、对齐、补零把字段排成整齐一行
impl fmt::Display for Invoice {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let amount = format!("{}.{:02}", self.cents / 100, self.cents % 100);
        let status = if self.paid { "PAID" } else { "DUE" };
        write!(f, "{:>4} {} {:>8}", self.id, status, amount)
    }
}

fn main() {
    let invoices = [
        Invoice { id: 7, cents: 4950, paid: true },
        Invoice { id: 1234, cents: 1234567, paid: false },
    ];
    for inv in &invoices {
        println!("|{inv}|");
    }
}

Inside the snippet

Count the functions fmt and main as the entire surface area of Implement Display With Width And Alignment.

Repetition is confined to for inv in &invoices — the rest of the file is straight-line.

Putting it to use

The main signature reads fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result

Core lines

fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let amount = format!("{}.{:02}", self.cents / 100, self.cents % 100);
let status = if self.paid { "PAID" } else { "DUE" };
write!(f, "{:>4} {} {:>8}", self.id, status, amount)
}

Interactive Tools for This Topic

FAQ

How do you run Implement Display With Width And Alignment?
Run it as a complete program — compile or interpret the file directly; there is nothing to install first.