泛型和 trait

2026-11-29 · Rust · Rust进阶

实验环境:rustc / cargo 1.93(Linux),文中代码、报错与输出均为实测。

入门线最后一篇说过要讲泛型。进阶篇从这里开始,先讲一对紧密配合的抽象:泛型让一份代码适用于多种类型,trait 定义"类型能做什么"。连接两者的就是"约束":告诉编译器这个 T 至少具备哪些能力。

泛型:把只差类型的重复代码合成一份

假设要找列表里最大的值。写两个版本,就是两个几乎一模一样的函数:

fn largest_i32(list: &[i32]) -> &i32 {
    let mut largest = &list[0];
    for item in list {
        if item > largest { largest = item; }
    }
    largest
}
fn largest_char(list: &[char]) -> &char {
    let mut largest = &list[0];
    for item in list {
        if item > largest { largest = item; }
    }
    largest
}
fn main() {
    let numbers = vec![34, 50, 25, 100, 65];
    println!("The largest number is {}", largest_i32(&numbers));   // 100
    let chars = vec!['y', 'm', 'a', 'q'];
    println!("The largest char is {}", largest_char(&chars));      // y
}

合成一份泛型版本:类型参数写在函数名后的 <> 里,按惯例用单个大写字母 T:

fn largest<T>(list: &[T]) -> &T {
    let mut largest = &list[0];
    for item in list {
        if item > largest { largest = item; }
    }
    largest
}

这份编译不过:

error[E0369]: binary operation `>` cannot be applied to type `&T`
help: consider restricting type parameter `T` with trait `PartialOrd`

原因很直白:T 代表任何类型,但不是所有类型都支持 > 比较。编译器直接提示你加约束——让 T 必须实现 PartialOrd 这个 trait(定义了可比较的行为):

fn largest<T: PartialOrd>(list: &[T]) -> &T {

改完之后同一个函数对 i32 和 char 都能用。泛型也能用在 struct、enum 和方法上,语法同一个路子:

struct Point<T> { x: T, y: T }

impl<T> Point<T> {
    fn x(&self) -> &T { &self.x }
}

fn main() {
    let p = Point { x: 5, y: 10 };
    println!("p.x = {}", p.x());   // p.x = 5
}

(你其实早就在用泛型了:Vec<T>、Option<T>、Result<T, E> 全是泛型类型。)

trait:把共享行为定义出来

trait 是一组方法签名的集合,声明"实现我的类型必须有这些能力"。比如一个新闻聚合器,希望不同内容类型都能给出摘要:

pub trait Summary {
    fn summarize(&self) -> String;
}

pub struct NewsArticle {
    pub headline: String,
    pub author: String,
}

impl Summary for NewsArticle {
    fn summarize(&self) -> String {
        format!("{}, by {}", self.headline, self.author)
    }
}

pub fn notify(item: &impl Summary) {   // 参数:任何实现了 Summary 的类型
    println!("Breaking news! {}", item.summarize());
}

fn main() {
    let article = NewsArticle {
        headline: String::from("Penguins win the Stanley Cup Championship!"),
        author: String::from("Iceburgh"),
    };
    notify(&article);
    // Breaking news! Penguins win the Stanley Cup Championship!, by Iceburgh
}

trait 里只写签名(分号结尾),各类型 impl trait名 for 类型 时填自己的实现。

默认实现:trait 里直接给方法写方法体,不想自定义的类型用空的 impl 就行:

pub trait Summary {
    fn summarize(&self) -> String { String::from("(Read more...)") }
}
pub struct NewsArticle { pub headline: String }
impl Summary for NewsArticle {}          // 用默认实现
fn main() {
    let a = NewsArticle { headline: String::from("Penguins win!") };
    println!("{}", a.summarize());       // (Read more...)
}

约束的两种写法:&impl Summary 是简写,完整形式是泛型参数加冒号约束 pub fn notify<T: Summary>(item: &T)。一个参数时两者等价,参数多了就有区别:(item1: &impl Summary, item2: &impl Summary) 允许两个参数类型不同;写成 <T: Summary>(item1: &T, item2: &T) 则强制两者同一类型。要多种能力就 + 起来:T: Summary + Display。

泛型不慢

Rust 的泛型靠单态化(monomorphization):编译期为每个实际用到的具体类型生成一份对应代码。largest(&numbers) 和 largest(&chars) 会变成两个具体的函数,运行开销和你手写两个版本完全一样——没有运行时查找,这点和"trait 对象"那种动态分发不同(dyn 是后面的内容)。

动手实践

把第一篇里两个重复函数写成泛型版,先故意不加约束,看 E0369 怎么直接点名要 PartialOrd;再自己定义一个 trait,给两个不同 struct 各写一份实现,然后用带约束的函数调用它们。下一篇讲生命周期——编译器不让你返回引用、报悬垂错误时,处理它的工具就是生命周期。

© 2026 michaelfu'site 原创文章,转载请注明出处:https://michaelfu.site/posts/2026-11-29-rust-generics-traits.html

← 返回首页