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?
CodePudding user response:
Minimized example:
fn main() {
println!("{} {:?}", 3.0, 3.0);
}
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.