如何使用超级特征作为参数?

时间:2017-07-31 20:20:20

标签: rust traits

我有一些2D位置的元素。由于它们中的大多数是(几乎)圆形,为了简化我使用距离来检查它们中的两个是否发生了碰撞。

虽然我可以从“父”特征中调用方法,但我 不能将其用作需要父特征的参数。

trait Point {
    fn x(&self) -> f64;
    fn y(&self) -> f64;
    fn distance(&self, other: &Point) -> f64 {
        ((other.x() - self.x()).powi(2) + (other.y() - self.y()).powi(2)).sqrt()
    }
}

trait Round: Point {
    fn radius(&self) -> f64;

    fn collision(&self, other: &Round) -> bool {
        let distance: f64 = self.distance(other);
        distance < self.radius() + other.radius()
    }
}
error[E0308]: mismatched types
  --> src/main.rs:13:43
   |
13 |         let distance: f64 = self.distance(other);
   |                                           ^^^^^ expected trait `Point`, found trait `Round`
   |
   = note: expected type `&Point`
              found type `&Round`

实现这一目标的正确方法是什么?

0 个答案:

没有答案