Rust - 泛型型別



泛型是編寫適用於多種不同型別上下文的程式碼的一種機制。在 Rust 中,泛型指的是資料型別和特徵的引數化。泛型允許編寫更簡潔、更清晰的程式碼,減少程式碼重複並提供型別安全。泛型的概念可以應用於方法、函式、結構體、列舉、集合和特徵。

<T> 語法稱為型別引數,用於宣告泛型構造。T 代表任何資料型別。

示例:泛型集合

以下示例宣告一個只能儲存整數的向量。

fn main(){
   let mut vector_integer: Vec<i32> = vec![20,30];
   vector_integer.push(40);
   println!("{:?}",vector_integer);
}

輸出

[20, 30, 40]

考慮以下程式碼片段:

fn main() {
   let mut vector_integer: Vec<i32> = vec![20,30];
   vector_integer.push(40);
   vector_integer.push("hello"); 
   //error[E0308]: mismatched types
   println!("{:?}",vector_integer);
}

以上示例表明,整數型別的向量只能儲存整數值。因此,如果嘗試將字串值推入集合,編譯器將返回錯誤。泛型使集合更具型別安全。

示例:泛型結構體

型別引數代表一個型別,編譯器稍後將填充該型別。

struct Data<T> {
   value:T,
}
fn main() {
   //generic type of i32
   let t:Data<i32> = Data{value:350};
   println!("value is :{} ",t.value);
   //generic type of String
   let t2:Data<String> = Data{value:"Tom".to_string()};
   println!("value is :{} ",t2.value);
}

以上示例聲明瞭一個名為Data的泛型結構體。<T>型別指示某種資料型別。main()函式建立了兩個例項——結構體的整數例項和字串例項。

輸出

value is :350
value is :Tom

特徵

特徵可用於在多個結構體中實現一組標準的行為(方法)。特徵就像面向物件程式設計中的介面。特徵的語法如下所示:

宣告一個特徵

trait some_trait {
   //abstract or method which is empty
   fn method1(&self);
   // this is already implemented , this is free
   fn method2(&self){
      //some contents of method2
   }
}

特徵可以包含具體方法(帶有方法體的方法)或抽象方法(沒有方法體的方法)。如果所有實現該特徵的結構體都將共享方法定義,則使用具體方法。但是,結構體可以選擇覆蓋特徵定義的函式。

如果實現結構體的方法定義有所不同,則使用抽象方法。

語法 - 實現一個特徵

impl some_trait for structure_name {
   // implement method1() there..
   fn method1(&self ){
   }
}

以下示例定義了一個具有print()方法的Printable特徵,該方法由book結構體實現。

fn main(){
   //create an instance of the structure
   let b1 = Book {
      id:1001,
      name:"Rust in Action"
   };
   b1.print();
}
//declare a structure
struct Book {
   name:&'static str,
   id:u32
}
//declare a trait
trait Printable {
   fn print(&self);
}
//implement the trait
impl Printable for Book {
   fn print(&self){
      println!("Printing book with id:{} and name {}",self.id,self.name)
   }
}

輸出

Printing book with id:1001 and name Rust in Action

泛型函式

此示例定義了一個泛型函式,該函式顯示傳遞給它的引數。引數可以是任何型別。引數的型別應該實現 Display 特徵,以便其值可以透過 println! 宏列印。

use std::fmt::Display;

fn main(){
   print_pro(10 as u8);
   print_pro(20 as u16);
   print_pro("Hello TutorialsPoint");
}

fn print_pro<T:Display>(t:T){
   println!("Inside print_pro generic function:");
   println!("{}",t);
}

輸出

Inside print_pro generic function:
10
Inside print_pro generic function:
20
Inside print_pro generic function:
Hello TutorialsPoint
廣告
© . All rights reserved.