1

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • 1
    *Generics are not the case, because I need to perform different arithmetic operations for each different integer variation* — [and you are sure you cannot do that with generics](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=769284e46ebbe66e7bb53a6f6362fc0a)? – Shepmaster Feb 03 '20 at 19:15
  • @Shepmaster, your comment is actually the answer for my question. Not the question you've marked my question to be duplicate to. – Alexander Vtyurin Feb 03 '20 at 19:24
  • That's the accepted answer in the linked duplicate: use generics. Since this question provided the restriction that generics may not be used (right or wrong), the other answer (use macros) could also suffice. – Shepmaster Feb 03 '20 at 19:26
  • @Shepmaster, there is no accepted answer (with check-mark on it) in the linked duplicate. Did you miss the link? Duplicate has a top-voted answer and it was about adding another level of indirection (Xed trait) - which (and it was mentioned in the first comment) doesn't solve the problem, because now you need to write Xed implementation with getters for each Point. – Alexander Vtyurin Feb 03 '20 at 19:35
  • @Shepmaster, anyway, thanks a lot! I hope someone like me will find your comment. – Alexander Vtyurin Feb 03 '20 at 19:37
  • True about the lack of accepted answer; I just saw it had many more votes and didn't think to validate that it was actually accepted! – Shepmaster Feb 03 '20 at 19:39

0 Answers0