Trait 定义与实现
trait 定义、impl Trait for Type、默认实现、派生宏 #[derive]
Trait 定义与实现
Trait 类似其他语言的接口——定义共享行为。Rust 的 trait 可以包含默认实现。
学完本章你将: 掌握 trait 定义、impl Trait for Type、#[derive] 派生。
定义与实现
rust
trait Summary {
fn summarize(&self) -> String;
// 带默认实现的方法
fn summarize_default(&self) -> String {
String::from("(阅读更多...)")
}
}
struct Article {
title: String,
content: String,
}
impl Summary for Article {
fn summarize(&self) -> String {
format!("{} - {}", self.title, &self.content[..50])
}
}
fn main() {
let article = Article {
title: String::from("Rust 入门"),
content: String::from("Rust 是一门系统编程语言..."),
};
println!("{}", article.summarize());
}
#[derive] 派生宏
rust
// 编译器自动实现常见 trait
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct User {
name: String,
age: u32,
}
let u1 = User { name: String::from("小明"), age: 25 };
let u2 = u1.clone();
println!("{:?}", u1); // Debug
println!("{}", u1 == u2); // true(PartialEq)
Orphan Rule(孤儿规则)
rust
// 只能为本地类型实现本地 trait
// impl Display for Vec<i32> { } // ❌ Vec 和 Display 都不是本地的
// ✅ 为本地类型实现外部 trait
struct MyVec(Vec<i32>);
impl std::fmt::Display for MyVec { ... }
// ✅ 为外部类型实现本地 trait
trait MyTrait { }
impl MyTrait for Vec<i32> { }