簡體   English   中英

Trait實現了Iterator,但是不能使用實現我的trait的結構作為Iterator

[英]Trait implements Iterator, but cannot use a struct implementing my trait as an Iterator

我有一個特性,我想說,如果一個結構實現了這個特性,那么它也可以充當Iterator 但是,當我嘗試使用struct作為迭代器時,我遇到了編譯器錯誤。

我正在編寫一個庫來從許多不同的文件格式中讀取相同類型的數據。 我想創建一個通用的“讀者”特征,它將返回適當的生銹對象。 我想說每個讀者都可以作為迭代器運行,產生該對象。

這是代碼

/// A generic trait for reading u32s
trait MyReader {
    fn get_next(&mut self) -> Option<u32>;
}

/// Which means we should be able to iterate over the reader, yielding u32s
impl Iterator for MyReader {
    type Item = u32;
    fn next(&mut self) -> Option<u32> {
        self.get_next()
    }
}

/// Example of a 'reader'
struct MyVec {
    buffer: Vec<u32>,
}

/// This can act as a reader
impl MyReader for MyVec {
    fn get_next(&mut self) -> Option<u32> {
        self.buffer.pop()
    }
}

fn main() {
    // Create a reader
    let mut veccy = MyVec { buffer: vec![1, 2, 3, 4, 5] };

    // Doesn't work :(
    let res = veccy.next();
}

編譯器輸出:

rustc 1.15.0 (10893a9a3 2017-01-19)
error: no method named `next` found for type `MyVec` in the current scope
  --> <anon>:31:21
   |
31 |     let res = veccy.next();
   |                     ^^^^
   |
   = help: items from traits can only be used if the trait is implemented and in scope; the following traits define an item `next`, perhaps you need to implement one of them:
   = help: candidate #1: `std::iter::Iterator`
   = help: candidate #2: `std::iter::ZipImpl`
   = help: candidate #3: `std::str::pattern::Searcher`

是生銹操場上的代碼。

在我看來,既然MyVec實現了MyReader ,那么它應該可以作為迭代器使用,因此我應該可以在它上面調用.next() 由於我已經實現了MyReader ,那么我應該免費獲得Iterator的實現,對吧? impl Iterator for ...表明Iterator在范圍內,所以我無法理解錯誤的來源。

這條線不符合你的想法。

impl Iterator for MyReader {

這實現了特征對象 MyReader Iterator 你想要的是為每個也實現MyReader類型實現Iterator 不幸的是,由於一致性規則,這是不可能的。

在Rust中,您只能在定義特征的包中或在定義要實現它的類型的包中實現特征。 (對於泛型類型來說事情有點復雜,但這是基本的想法。)在這種情況下, Iterator是標准庫的特征,所以沒有辦法在你沒有定義的任意類型上實現它。 如果你考慮一下,這是有道理的,因為如果其中一個類型有一個預先存在的Iterator實現 - 你將使用哪一個,你會變得模棱兩可?

一種解決方案是將實現MyReader的類型包裝在MyReader中,並在其上實現Iterator 由於您自己定義了newtype,因此可以自由地在其上實現Iterator

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM