■ 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 45 46 47 48 49 50 51 52 53 54 55 |
pub trait Summarizable { fn summary(&self) -> String; } pub struct News { pub headline : String, pub location : String, pub author : String, pub content : String } impl Summarizable for News { fn summary(&self) -> String { return format!("{}, by {} ({})", self.headline, self.author, self.location); } } pub struct Tweet { pub user_name : String, pub content : String, pub reply : bool, pub retweet : bool } impl Summarizable for Tweet { fn summary(&self) -> String { return format!("{} : {}", self.user_name, self.content); } } 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 : horse_ebooks : of course, as you probably already know, people */ |