2014-09-25 52 views
3

我嘗試寫一些基本的通用:防鏽:仿製藥PartialEq特質

pub struct MyGeneric<T> { 
    vec: Vec<T> 
} 

impl<T> MyGeneric<T> { 
    fn add(&mut self, item: T) { 
     if !self.vec.contains(&item) { 
      self.vec.push(item); 
     } 
    } 
} 

,但得到的錯誤:

priority_set.rs:23:10: 23:35 error: the trait `core::cmp::PartialEq` is not implemented for the type `T` 
priority_set.rs:23  if !self.vec.contains(&item) { 
          ^~~~~~~~~~~~~~~~~~~~~~~~~ 
error: aborting due to previous error 

我試圖實現PartialEq在幾個方面尋找到API文件,但沒有找到自己的解決方案。我對性狀概念不是很熟悉,所以我需要幫助。

謝謝。

回答

5

您需要限制所有可能的值T來實現PartialEq的,因爲Vec::contains()定義需要它:

pub struct MyGeneric<T> { 
    vec: Vec<T> 
} 

// All you need is to add `: PartialEq` to this impl 
// to enable using `contains()` 
impl<T: PartialEq> MyGeneric<T> { 
    fn add(&mut self, item: T) { 
     if !self.vec.contains(&item) { 
      self.vec.push(item); 
     } 
    } 
} 

fn main() 
{ 
    let mut mg: MyGeneric<int> = MyGeneric { vec: Vec::new() }; 
    mg.add(1); 
} 

泛型類型需要指定自己的參數大部分時間一些界限,否則將無法驗證通用代碼是否正確。在此,例如,正在使用運算符==上的項目,但並非每種類型都可以定義該運算符。標準特質PartialEq定義了運算符==,因此實現該特徵的所有內容都保證具有該運算符。

+0

您能否擴展您的示例代碼?我想我已經開始瞭解,但不太確定。 – bbrodriges 2014-09-25 11:32:25

+0

@ bender.rodriges我已經包含了在Rust 0.11中編譯的最小示例。 – hamstergene 2014-09-25 11:34:33

+0

現在我明白了!我確實認爲符號意味着派生。所有這一次我試圖像fmt :: Show trait一樣實現它。謝謝! – bbrodriges 2014-09-25 11:38:04