Rust 的 trait 是定义类型行为的核心机制,类似于其他语言中的接口(interface),但功能更强大。它是 Rust 实现多态(polymorphism)和抽象的核心工具。
定义 trait
使用 trait
关键字定义一组方法签名(可包含默认实现):
trait HasArea {
fn area(&self) -> f64;
fn print_area(&self) {
println!("面积是:{}", &self.area());
}
}
HasArea规定了实现者必需有 area(&self) -> f64方法。还实现了带默认方法的print_area。这是特性与接口的不同点:接口只能规范方法而不能定义方法,但特性可以定义方法作为默认方法,因为是"默认",所以对象既可以重新定义方法,也可以不重新定义方法使用默认的方法:
为类型实现 trait
impl <特性名> for <所实现的类型名>
Rust 同一个类可以实现多个特性,每个 impl 块只能实现一个。
struct Circle {
x: f64,
y: f64,
radius: f64,
}
impl HasArea for Circle {
fn area(&self) -> f64 {
std::f64::consts::PI * (self.radius * self.radius)
}
}
struct Square {
x: f64,
y: f64,
side: f64,
}
impl HasArea for Square {
fn area(&self) -> f64 {
self.side * self.side
}
}
2. 核心用法
作为接口使用
通过 trait 约束泛型类型的行为:
fn print_area<T: HasArea>(shape: &T) {
println!("shape 的面积是 {}", shape.area());
}
fn main() {
let c = Circle { x: 0.0, y: 0.0, radius: 1.0 };
let s = Square { x: 0.0, y: 0.0, side: 2.0 };
print_area(&c);
print_area(&s);
}
动态分发(Trait 对象)
使用 dyn Trait
实现运行时多态,即在运行时决定调用哪个方法,这可以通过 Trait 对象来实现。Trait 对象允许你存储不同类型的值,只要这些类型实现了相同的 Trait。
fn print_area_dyn(shape: &dyn HasArea) {
println!("shape 的面积是 {}", shape.area());
}
fn main() {
let c = Circle { x: 0.0, y: 0.0, radius: 1.0 };
let s = Square { x: 0.0, y: 0.0, side: 2.0 };
print_area_dyn(&c);
print_area_dyn(&s);
}
3. 高级特性
关联类型(Associated Types)
在 trait 中定义类型占位符,由实现者指定具体类型:
trait Iterator {
type Item; // 关联类型
fn next(&mut self) -> Option<Self::Item>;
}
struct Counter(u32);
impl Iterator for Counter {
type Item = u32;
fn next(&mut self) -> Option<Self::Item> {
self.0 += 1;
Some(self.0)
}
}
泛型 trait
定义带泛型参数的 trait:
trait Converter<T> {
fn convert(&self) -> T;
}
impl Converter<String> for i32 {
fn convert(&self) -> String {
self.to_string()
}
}
Trait 继承
一个 trait 可以继承多个父 trait:
trait Animal {
fn name(&self) -> &str;
}
trait Mammal: Animal { // 继承 Animal
fn walk(&self) {
println!("{} is walking", self.name());
}
}
struct Dog;
impl Animal for Dog {
fn name(&self) -> &str { "Dog" }
}
impl Mammal for Dog {}
fn main() {
let d = Dog{};
d.name();
d.walk();
}
4. 对象安全(Object Safety)
只有满足以下条件的 trait 才能作为 trait 对象(dyn Trait
)使用:
方法不返回
Self
。方法没有泛型参数。
Trait 不要求
Self: Sized
约束。
示例(非对象安全的 trait):
trait Cloneable {
fn clone(&self) -> Self; // 返回 Self,违反对象安全
}
// 错误!无法转换为 `dyn Cloneable`
let obj: Box<dyn Cloneable> = Box::new(42);
5. 常见标准库 Trait
Clone / Copy:复制语义。
Debug / Display:格式化输出。
PartialEq / Eq:相等比较。
PartialOrd / Ord:排序比较。
From / Into:类型转换。
Default:默认值。
Drop:自定义析构逻辑。
6. 典型使用场景
多态行为抽象(如 GUI 组件的 draw 方法)。
泛型约束(限制泛型类型的能力)。
运算符重载(通过实现 Add、Mul 等 trait)。
错误处理(标准 Error trait)。
迭代器模式(Iterator trait)。
总结
Trait 在 Rust 中是非常强大的工具,用于定义共享行为、实现多态性以及提供灵活的接口设计。通过 Trait,你可以编写高度模块化和可复用的代码,同时保持静态类型系统的安全性和性能优势。无论是简单的接口定义还是复杂的泛型编程,Trait 都能提供所需的功能和支持。