0

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?

3
  • 1
    Note that println!("{}", 3.0f64) also prints 3 so this is just how the Display implementation of floats works. Commented Aug 31, 2022 at 12:43
  • If you use {:?} in your print() function, you should see the decimal point. Commented Aug 31, 2022 at 12:46
  • 1
    "{:?}" marker formats arguments in Debug mode, "{}" marker formats arguments in Display mode: and their implementations: doc.rust-lang.org/src/core/fmt/float.rs.html#193, for other kinds of formats you can check this link: doc.rust-lang.org/std/fmt/index.html#traits Commented Aug 31, 2022 at 12:49

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Additional remark: if you want a specific precision shown, println expects you to specify that explicitly: stackoverflow.com/questions/26576889/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.