首页 > 解决方案 > 如何以相同的方式为多种不同类型实现 Display 特征?

问题描述

我有接下来的几个结构。

struct PointI8 {
    x: i8,
    y: i8,
}

struct PointI64 {
    x: i64,
    y: i64,
}

为了漂亮地打印它们,我需要为Display它们中的每一个实现特征:

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)
    }
}

每个结构的实现几乎相同。

我怎样才能摆脱这个样板?泛型(在某种意义上Point<T: Display>)并非如此,因为我需要为每个不同的整数变化执行不同的算术运算。我来自 Kotlin,在 Kotlin 中我会做这样的事情:

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
}

我怎样才能在 Rust 中实现同样的目标?

标签: rusttraits

解决方案


推荐阅读