Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to pass formatting expression in Rust?

For example, I have a very simple struct which contains only a float, but I want to implement the Display trait for this struct while also be able to set precision for the float inside of the struct…
Sorry I’m very bad at describing things, here’s the sample code:

struct NewFloat(f64);

impl std::fmt::Display for NewFloat {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.pad(&self.0.to_string())
    }
}

fn main() {
    let test: NewFloat = NewFloat(0.046);
    println!("{:.2}", test);    // 0.
    println!("{:.2}", 0.046);   // 0.05
}

I’d prefer printing test giving me same result as printing 0.046, which applies precision to floating points only and also rounds the number, how do I do that?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can simply delegate to the existing implementation for field:

impl std::fmt::Display for NewFloat {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
        // or, for more explicitness:
        // std::fmt::Display::fmt(&self.0, f)
    }
}

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading