// 建立方法抽象層 traitAction { // function do 返回不指定,可自定義 fnsay_hello(&self); // function can_do 返回 true or false fncan_do(&self) -> bool; }
// 實作方法 by using trait for struct // 同樣性質的trait, 可以用來實作多個結構體, // 使用 `for` -> 專屬哪個struct impl Action for People { // &self 使用自己的意思 fnsay_hello(&self) { println!("Hello, my name is {}.", self.name) }
fnmain() { let people_1 = People { // new 一個新的String出來 name: String::from("Kylls"), age: 18, };
println!("Can {} speak? {}", people_1.name, people_1.can_do()); // output: Can Kylls speak? true people_1.say_hello(); // output: Hello, my name is Kylls.