简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM