高级特征 #
一、关联类型 #
rust
trait Container {
type Item;
fn get(&self) -> Option<&Self::Item>;
}
struct VecContainer<T> {
items: Vec<T>,
}
impl<T> Container for VecContainer<T> {
type Item = T;
fn get(&self) -> Option<&Self::Item> {
self.items.first()
}
}
二、默认类型参数 #
rust
trait Add<Rhs = Self> {
type Output;
fn add(self, rhs: Rhs) -> Self::Output;
}
三、完全限定语法 #
rust
trait Pilot {
fn fly(&self);
}
trait Wizard {
fn fly(&self);
}
struct Human;
impl Pilot for Human {
fn fly(&self) {
println!("机长飞行");
}
}
impl Wizard for Human {
fn fly(&self) {
println!("巫师飞行");
}
}
fn main() {
let person = Human;
Pilot::fly(&person);
Wizard::fly(&person);
}
四、总结 #
本章学习了:
- 关联类型
- 默认类型参数
- 完全限定语法
最后更新:2026-03-27