I have the next several structs.
struct PointI8 {
x: i8,
y: i8,
}
struct PointI64 {
x: i64,
y: i64,
}
To pretty-print them, I need to implement Display
trait for each of them:
impl fmt::Display for PointI8 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "({}, {})", self.x, self.y)
}
}
impl fmt::Display for PointI64 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "({}, {})", self.x, self.y)
}
}
The implementations are almost the same for each struct.
How can I get rid of this boilerplate? Generics (in a sense of Point<T: Display>
) are not the case, because I need to perform different arithmetic operations for each different integer variation.
I'm from Kotlin and in Kotlin I would do something like this:
abstract class AbstractPoint<T> {
abstract val x: T
abstract val y: T
override fun toString() = x.toString() + y.toString()
}
// now I can create as more Point<Something> classes as I want
// they would all have toString() implemented
// and I also can perform different operations for each variation of this class
class PointByte: AbstractPoint<Byte>() {
override val x: Byte = 0
override val y: Byte = 0
}
How can I achieve the same thing in Rust?