問題一覧に戻る
中級トレイト
問題64: トレイトの実装
既存の型に標準ライブラリのトレイトを実装できます。Displayで表示形式を定義、Addで演算子オーバーロードを実現します。孤児ルールにより、外部クレートの型とトレイトの組み合わせには制限があります。型に新しい機能を追加する強力な方法です。
use std::fmt;
struct Point {
x: i32,
y: i32,
}
// Displayトレイト実装
impl fmt:: for Point {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt:: {
write!(f, "({}, {})", self.x, self.y)
}
}
// Addトレイト実装
impl std::ops:: for Point {
type Output = ;
fn add(self, other: Self) -> Self::Output {
Point {
x: self.x + other.x,
y: self.y + other.y,
}
}
}
fn main() {
let p1 = Point { x: 1, y: 2 };
let p2 = Point { x: 3, y: 4 };
println!("{} + {} = {}", p1, p2, p1 p2);
}