Updated src/generic_types_traits_and_lifetimes/traits.md'.

This commit is contained in:
Hector PENG
2026-03-22 17:43:16 +08:00
parent d6b64ff021
commit 563c824115
3 changed files with 48 additions and 37 deletions

View File

@@ -1,5 +1,9 @@
pub trait Summary {
fn summarize(&self) -> String;
fn summarize_author(&self) -> String;
fn summarize(&self) -> String {
format! ("(阅读更多来自 {} ......", self.summarize_author())
}
}
pub struct NewsArticle {
@@ -10,8 +14,8 @@ pub struct NewsArticle {
}
impl Summary for NewsArticle {
fn summarize(&self) -> String {
format! ("{}, by {} ({})", self.headline, self.author, self.location)
fn summarize_author(&self) -> String {
format! ("by {}", self.author)
}
}
@@ -23,7 +27,7 @@ pub struct SocialPost {
}
impl Summary for SocialPost {
fn summarize(&self) -> String {
format! ("{}: {}", self.username, self.content)
fn summarize_author(&self) -> String {
format! ("@{}", self.username)
}
}

View File

@@ -1,4 +1,4 @@
use aggregator::{SocialPost, Summary};
use aggregator::{SocialPost, Summary, NewsArticle};
fn main() {
let post = SocialPost {
@@ -10,5 +10,18 @@ fn main() {
retweet: false,
};
println!("1 个新帖子: {}", post.summarize());
println! ("1 个新帖子{}", post.summarize());
let article = NewsArticle {
headline: String::from("企鹅队赢得斯坦利杯锦标赛!"),
location: String::from("美国,宾夕法尼亚州,匹兹堡"),
author: String::from("Iceburgh"),
content: String::from(
"匹兹堡企鹅队再度成为美国曲棍球联盟 \
NHL 中的最佳球队。"
),
};
println! ("有新文章可读!{}", article.summarize());
}