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

Rust float formatted as integer by generics

I have the following Rust code:

#[derive(Debug)]
struct Point<T, U> {
    x: T,
    y: U
}

impl<T: std::fmt::Display, U: std::fmt::Display> Point<T, U> {
    fn print(&self) {
        println!("{} {}", &self.x, &self.y );
    }
}

impl<X1, Y1> Point<X1, Y1> {
    fn mixup<X2, Y2>(self, other: Point<X2, Y2>) -> Point<X1, Y2> {
        Point {
            x: self.x,
            y: other.y,
        }
    }
}

fn main() {
    let integer = Point {x: 1, y:2};
    let float = Point{x: 2.0, y:3.0};

    let floaty = integer.mixup(float);

    println!("{:?}", floaty); // output: Point { x: 1, y: 3.0 } - OK
    floaty.print(); // output: 1 3 - NOT OK
}

Why does floaty.print() coerce 3.0 to 3? Is there anything wrong with how the print method is implemented?

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 :

Minimized example:

fn main() {
    println!("{} {:?}", 3.0, 3.0);
}

(Playground)

This prints 3 3.0, i.e. floats which don’t have a fractional part are formatted via Display as integers. That’s not something wrong with print function – just the fact that Display implies human-readable output, and for human-readable output it is chosen to print integers where possible.

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