Search code examples
rustdisplayformatter

In Rust, when implementing the trait `Display`, how to obtain the formatting specified by the caller?


Given this Rust program, which prints 1.23456:

use std::fmt;
struct Foo(f64);
impl fmt::Display for Foo {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{}", self.0)
    }
}
fn main() {
    println!("{:.2}", Foo(1.23456));
}

Which the simplest change to the body of the function fmt, to get printed 1.23? In general, is there a simple way to use inside the function fmt the same formatting options set by the code which prints the object? I know the formatter object has several methods which access formatting options, but is there a simple method to obtain always the same result which is obtained by calling println!("{:.2}", Foo(1.23456).0);?


Solution

  • To pass all formatting options to .0, you can just call .fmt on it:

    use std::fmt;
    struct Foo(f64);
    impl fmt::Display for Foo {
        fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
            self.0.fmt(formatter)
        }
    }
    fn main() {
        println!("{:.2}", Foo(1.23456));
    }
    

    (See playground)