トレイト(trait)は、構造体にルールを定義する
struct Dog { name: String, age: i32, } struct Cat { name: String, age: i32, } trait Cry { fn cry(&self); } impl Cry for Dog { fn cry(&self) { println!("わんわん"); } } impl Cry for Cat { fn cry(&self) { println!("にゃお"); } } fn main() { let d = Dog {name: String::from("ポチ"), age: 6}; println!("{}({})", d.name, d.age); d.cry(); let c = Cat {name:String::from("タマ"), age:4}; println!("{}({})", c.name, c.age); c.cry(); }
### ジェネリックなメソッド
struct Point<T, U> { x: T, y: U, } trait Printdata { fn print(&self); } impl<T, U> Printdata for Point<T, U> where T: std::fmt::Display, U: std::fmt::Display { fn print(self: &Point<T, U>){ println!("({}, {})", self.x, self.y); } } fn main(){ let p1 = Point { x: 20, y: 10}; let p2 = Point { x: 5, y: 6.0}; p1.print(); println!("p2.X={}, p2.y={}", p2.x, p2.y); }
所有権とトレイト
struct Point { x: i32, y: i32, } fn main(){ let p = Point {x: 12, y:25}; print(p); println!("({}, {})", p.x, p.y); } fn print(p:Point) { println!("({}, {})", p.x, p.y); }
### clone()
struct Point { x: i32, y: i32, } impl Clone for Point { fn clone(&self) -> Self { Point { x: self.x.clone(), y: self.y.clone(), } } } fn main(){ let p = Point {x: 12, y:25}; print(p.clone()); println!("({}, {})", p.x, p.y); } fn print(p:Point) { println!("({}, {})", p.x, p.y); }