rust - 如何以相同的方式为多种不同类型实现 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 中实现同样的目标?
解决方案
推荐阅读
- microsoft-graph-api - 查询 149 天以上时,MS Graph API CalendarView 是否存在问题?
- android - Android 项目添加 Flutter 模块抛出 MissingPluginException
- c# - 在 LINQ .netcore 3.1 中按 DATEPART 和 DATEDIFF 分组
- python - 循环并创建一个考虑闰年的日期列表
- reactjs - 使用 props 和 useState Hook 从 Child 中的输入更新父组件的状态
- python - Django - 在最终保存之前编辑上传的文件
- google-bigquery - 使用 BigQuery 查找最常见的字符串值
- c# - 有没有办法接受使用 C# 静默安装 .msi 文件的许可协议?
- javascript - 每当按下光标或箭头键时,如何获取当前光标位置(在文本区域中)?
- python - 使用 UpdateCursor 在 ArcMap 中拆分字符串并更新字段