【07】trait特性
文章目录
- Trait
- 为类型实现trait
- 为trait提供默认实现
- 使用trait作为参数
- trait bound
- 使用trait作为返回值
Trait
感觉可以类比C++中父类的虚函数
类似其他语言中的接口,定义了某个特定类型与其他特定类型共享的功能。
为类型实现trait
trait的实现需要满足 trait
与类型至少有一个在当前crate中。是为了防止外部代码破坏crate。
- 给已有类型添加
trait
- 给新类型添加trait实现
// 定义trait
pub trait Summary {fn summarize(&self) ->String;
}// 具体数据类型
pub strcut NewArticle {pub headline: String,pub location: String,pub author: String,pub content: String,
}
// 将trait引入具体类型
impl Summary for NewArticle {fn summarize(&self) -> String {format!("{}, by {} ({})", self.headline, self.author, self.location)}
}