翻译尚未覆盖全部内容。完整技术参考请查阅英文原文。 查看英文版本 →

Traits

Define shared behavior across types with trait declarations and implementations.

Trait

Trait 定义了多种类型可以实现的共享接口。它是 Sounio 实现有界多态(bounded polymorphism)的机制 —— 函数可以要求其类型参数实现特定的 trait。

声明 trait

trait Printable {
    fn to_string(self) -> str
}

trait Measurable {
    fn magnitude(self) -> f64
}

实现 trait

struct Point { x: f64, y: f64 }

impl Printable for Point {
    fn to_string(self) -> str {
        format("({}, {})", self.x, self.y)
    }
}

impl Measurable for Point {
    fn magnitude(self) -> f64 {
        sqrt(self.x * self.x + self.y * self.y)
    }
}

Trait 约束

使用 trait 约束来限制泛型类型参数:

fn display<T: Printable>(value: T) with IO {
    println(value.to_string())
}

fn compare_magnitudes<T: Measurable>(a: T, b: T) -> bool {
    a.magnitude() > b.magnitude()
}

Trait 检查的位置

Trait 解析实现在 self-hosted/check/traits.sio 中。检查器验证:

  • 每个 impl 块提供了所有必需的方法。
  • impl 中的方法签名与 trait 声明匹配。
  • 调用处的 trait 约束被具体类型所满足。

当前状态

当前的解析器和类型检查器支持 trait 声明、实现和简单约束。更高级的特性(关联类型、默认方法、trait 继承)在功能状态页面中跟踪。