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?
println!("{}", 3.0f64)also prints3so this is just how theDisplayimplementation of floats works.{:?}in yourprint()function, you should see the decimal point."{:?}"marker formats arguments inDebugmode,"{}"marker formats arguments inDisplaymode: 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