Rust从入门到实战系列九十八:返回实现了 trait 的类型

也可以在返回值中使用 impl Trait 语法,来返回实现了某个 trait 的类型:

# fn summarize(&self) -> String;
# }
#
# pub struct NewsArticle {
# pub headline: String,
# pub location: String,
# pub author: String,
# pub content: String,
# }
#
# impl Summary for NewsArticle {
# fn summarize(&self) -> String {
# format!("{}, by {} ({})", self.headline, self.author, self.location)
# }
# }
#
# pub struct Tweet {
# pub username: String,
# pub content: String,
# pub reply: bool,
# pub retweet: bool,
# }
#
# impl Summary for Tweet {
# fn summarize(&self) -> String {
# format!("{}: {}", self.username, self.content)
# }
# }
#
fn returns_summarizable() -> impl Summary {
Tweet {
username: String::from("horse_ebooks"),
content: String::from(
"of course, as you probably already know, people",
),
reply: false,
retweet: false,
}
}

通过使用 impl Summary 作为返回值类型,我们指定了 returns_summarizable 函数返回某个实现了Summary trait 的类型,但是不确定其具体的类型。在这个例子returns_summarizable 返回了一个Tweet,不过调用方并不知情。
返回一个只是指定了需要实现的 trait 的类型的能力在闭包和迭代器场景十分的有用,第十三章会介绍它们。闭包和迭代器创建只有编译器知道的类型,或者是非常非常长的类型。impl Trait 允许你简单的指定函数返回一个 Iterator 而无需写出实际的冗长的类型。
不过这只适用于返回单一类型的情况。例如,这段代码的返回值类型指定为返回 impl Summary,但是返回了 NewsArticle 或 Tweet 就行不通:

# fn summarize(&self) -> String;
# }
#
# pub struct NewsArticle {
# pub headline: String,
# pub location: String,
# pub author: String,
# pub content: String,
# }
#
# impl Summary for NewsArticle {
# fn summarize(&self) -> String {
# format!("{}, by {} ({})", self.headline, self.author, self.location)
# }
# }
#
# pub struct Tweet {
# pub username: String,
# pub content: String,
# pub reply: bool,
# pub retweet: bool,
# }
#
# impl Summary for Tweet {
# fn summarize(&self) -> String {
# format!("{}: {}", self.username, self.content)
# }
# }
#
fn returns_summarizable(switch: bool) -> impl Summary {
if switch {
NewsArticle {
headline: String::from(
"Penguins win the Stanley Cup Championship!",
),
location: String::from("Pittsburgh, PA, USA"),
author: String::from("Iceburgh"),
content: String::from(
"The Pittsburgh Penguins once again are the best \
hockey team in the NHL.",
),
}
} else {
Tweet {
username: String::from("horse_ebooks"),
content: String::from(
"of course, as you probably already know, people",
),
reply: false,
retweet: false,
}
}
}

这里尝试返回 NewsArticle 或 Tweet。这不能编译,因为 impl Trait 工作方式的限制。第十七章的 ” 为使用不同类型的值而设计的 trait 对象” 部分会介绍如何编写这样一个函数。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值