Rust 泛型

泛型可以使用在结构体中

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

其中x,y都属于T类型。

实现结构体的方法或者关联函数需要在impl关键字后面指定泛型

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

讲到泛型就绕不开trait,trait类似于其他语言中的接口

具体使用方法如下

pub trait Summarizable {
    fn summary(&self) -> String;
}
pub struct NewsArticle {
    pub headline: String,
    pub location: String,
    pub author: String,
    pub content: String,
}

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

要希望泛型拥有特定的功能,就必须指定泛型的trait,简称trait bound

impl<T: Display + PartialOrd> Pair<T> {
    fn cmp_display(&self) {
        if self.x >= self.y {
            println!("The largest member is x = {}", self.x);
        } else {
            println!("The largest member is y = {}", self.y);
        }
    }
}

泛型T要有比较和打印功能,就要指定T的trait bound

有一个易于观看的trait bound语法

fn some_function<T, U>(t: T, u: U) -> i32
    where T: Display + Clone,
          U: Clone + Debug
{
}

也可以这样写

fn some_function<T: Display + Clone, U: Clone + Debug>(t: T, u: U) -> i32 {
}