Rust Trait系统:从入门到高级
3 阅读
预计 3 分钟
Trait是Rust实现多态和代码复用的核心机制。本文从基础到高级全面讲解。
## 定义与实现Trait
```rust
trait Summary {
fn summarize_author(&self) -> String;
fn summarize(&self) -> String {
format!("(Read more from {}...)", self.summarize_author())
}
}
struct Article {
title: String,
author: String,
content: String,
}
impl Summary for Article {
fn summarize_author(&self) -> String {
self.author.clone()
}
fn summarize(&self) -> String {
format!("{}, by {}", self.title, self.author)
}
}
```
## Trait作为参数
```rust
fn notify(item: &impl Summary) {
println!("Breaking news! {}", item.summarize());
}
fn notify(item: &T) {
println!("Breaking news! {}", item.summarize());
}
fn notify(item: &T) {}
```
## Trait对象
```rust
fn returns_summarizable() -> Box {
Box::new(Article {
title: String::from("Rust Traits"),
author: String::from("Alice"),
content: String::from("Trait content"),
})
}
```
## 常用标准库Trait
- Clone / Copy:值复制语义
- Debug:格式化输出
- Default:默认值
- From / Into:类型转换
- Iterator:迭代器
- Read / Write:IO操作
## 关联类型
```rust
trait Container {
type Item;
fn get(&self) -> &Self::Item;
}
```
Trait是Rust最强大的特性之一,掌握它是成为Rust高手的关键。
0 条评论 欢迎参与讨论