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 {
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM