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.
Code
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
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.