泛型

泛型让我们编写可适用于多种类型的代码。

泛型函数

fn largest<T: PartialOrd>(list: &[T]) -> &T {
    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];
    let result = largest(&numbers);
    println!("最大值: {}", result);

    let chars = vec!['y', 'm', 'a', 'q'];
    let result = largest(&chars);
    println!("最大字符: {}", result);
}

泛型结构体

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

impl<T> Point<T> {
    fn new(x: T, y: T) -> Self {
        Point { x, y }
    }

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

// 为特定类型实现方法
impl Point<f32> {
    fn distance_from_origin(&self) -> f32 {
        (self.x.powi(2) + self.y.powi(2)).sqrt()
    }
}

fn main() {
    let integer_point = Point::new(5, 10);
    let float_point = Point::new(1.0, 4.0);

    println!("距离原点: {}", float_point.distance_from_origin());
}

泛型枚举

enum Option<T> {
    Some(T),
    None,
}

enum Result<T, E> {
    Ok(T),
    Err(E),
}

fn main() {
    let some_number: Option<i32> = Some(5);
    let some_string: Option<String> = Some(String::from("hello"));
    let absent: Option<i32> = None;
}

多个泛型参数

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

fn main() {
    let mixed = Point { x: 5, y: 4.0 };  // T=i32, U=f64
}

泛型约束

use std::fmt::Display;

fn print_two<T: Display + Clone, U: Clone + Debug>(t: T, u: U) {
    println!("{}", t);
}

// where 子句(更易读)
fn print_two_where<T, U>(t: T, u: U)
where
    T: Display + Clone,
    U: Clone + Debug,
{
    println!("{}", t);
}

单态化

Rust 在编译时为每个具体类型生成专用代码:

let integer = Some(5);   // 编译为 Option_i32
let float = Some(5.0);   // 编译为 Option_f64

零成本抽象:泛型没有运行时开销!

关联类型

trait Iterator {
    type Item;  // 关联类型

    fn next(&mut self) -> Option<Self::Item>;
}

struct Counter {
    count: u32,
}

impl Iterator for Counter {
    type Item = u32;

    fn next(&mut self) -> Option<Self::Item> {
        self.count += 1;
        if self.count < 6 {
            Some(self.count)
        } else {
            None
        }
    }
}

小结

  • ✅ 泛型提供代码复用
  • ✅ 使用 <T> 语法声明泛型类型
  • ✅ 可以对泛型添加 trait 约束
  • ✅ 单态化保证零运行时开销
  • ✅ 关联类型简化 trait 定义