Support Alternate {:#} Mode In Display

Check Formatter::alternate() inside a custom std::fmt::Display impl so {} emits a compact one-line summary while {:#} prints a multi-line breakdown.

RustCli Tooling

Code

rustsnippet
34 lines
use std::fmt;

struct EndpointReport {
    service: &'static str,
    status: u16,
    latency_ms: u32,
    region: &'static str,
}

impl fmt::Display for EndpointReport {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if f.alternate() {
            writeln!(f, "EndpointReport {{")?;
            writeln!(f, "  service: {},", self.service)?;
            writeln!(f, "  status:  {},", self.status)?;
            writeln!(f, "  latency: {}ms,", self.latency_ms)?;
            write!(f, "  region:  {}\n}}", self.region)
        } else {
            write!(f, "{} [{}] {}ms ({})", self.service, self.status, self.latency_ms, self.region)
        }
    }
}

fn main() {
    let report = EndpointReport {
        service: "checkout-api",
        status: 200,
        latency_ms: 18,
        region: "eu-west-1",
    };

    println!("compact: {report}");
    println!("expanded:\n{report:#}");
}

Logic trace — Support Alternate {:#} Mode In Display

Follow the execution flow beginning at helpers fmt and main, doing all the work.

What to watch for

  • Exclusively built-in runtime APIs so zero external package supply chains appear.

Putting it to use

The entry-point signature is fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result

Logged output lines emit labels — compact:, expanded:\n — when the file runs.

Core lines

writeln!(f, "  latency: {}ms,", self.latency_ms)?;
writeln!(f, "  service: {},", self.service)?;
writeln!(f, "  status:  {},", self.status)?;

Interactive Tools for This Topic

FAQ

What does Support Alternate {:#} Mode In Display print when run?
Running the file directly is enough — expect labeled output lines such as `compact:`, `expanded:\n`.