複数の Trait による Restriction

Generics の restriction に複数の trait を指定したい場合、+ を使えばいいらしい。

struct Circle {
    x: f64,
    y: f64,
    radius: f64,
}

trait HasArea {
    fn area(&self) -> f64;
}

trait HasPoint {
    fn point(&self) -> (f64, f64);
}

impl HasArea for Circle {
    fn area(&self) -> f64 {
        std::f64::consts::PI * (self.radius * self.radius)
    }
}

impl HasPoint for Circle {
    fn point(&self) -> (f64, f64) {
        (self.x, self.y)
    }
}

fn print_area_and_point<T: HasArea+HasPoint>(c: T) {
    println!("area is {}, {}", c.area(), c.point());
}

fn main() {
    let c = Circle{x: 0.0, y:0.0, radius: 1.0};
    print_area_and_point(c);
}

http://melpon.org/wandbox/permlink/TH9xztDKwDhjoyYz