■ trait 키워드에서 메소드를 호출하는 기본 구현 메소드를 만드는 방법을 보여준다.
▶ 예제 코드 (RS)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
pub trait Summarizable { fn author_summary(&self) -> String; fn summary(&self) -> String { format!("(Read more from {}...)", self.author_summary()) } } pub struct Tweet { pub user_name : String, pub content : String, pub reply : bool, pub retweet : bool } impl Summarizable for Tweet { fn author_summary(&self) -> String { return format!("@{}", self.user_name); } } fn main() { let tweet : Tweet = Tweet { user_name : String::from("horse_ebooks"), content : String::from("of course, as you probably already know, people"), reply : false, retweet : false }; println!("1 new tweet : {}", tweet.summary()); } /* 1 new tweet : (Read more from @horse_ebooks...) */ |