2017-09-09 72 views
1

全部鏽例如這裏: https://play.rust-lang.org/?gist=0778e8d120dd5e5aa7019bc097be392b&version=stable自壽命

總的想法是爲執行一個通用的迭代分割,將產生迭代器對於由指定的分隔分裂值的每次運行。因此,對於[1, 2, 3, 0, 4, 5, 6, 0, 7, 8, 9],split(0)你會得到[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

對於此代碼:

impl<'a, I, F> Iterator for Split<I, F> 
    where I: Iterator, 
      F: PartialEq<I::Item>, 
{ 
    type Item = SplitSection<'a, I, F>; 
    fn next(&'a mut self) -> Option<Self::Item> { 
     self.iter.peek().map(|_| 
     SplitSection { 
      exhausted: false, 
      iter: self, 
     }) 
    } 
} 

我收到以下錯誤:

error[E0207]: the lifetime parameter `'a` is not constrained by the impl trait, self type, or predicates 
    --> src/main.rs:22:6 
    | 
22 | impl<'a, I, F> Iterator for Split<I, F> 
    |  ^^ unconstrained lifetime parameter 

有沒有一種方法來「約束」的壽命參數,或以某種方式重構它,以便關聯的類型(Item)返回一個生命週期,並將其綁定到next()?

基本上,由於每個SplitSection使用Split擁有的迭代器,我想確保兩個SplitSection不會一次迭代。

謝謝!

回答

2

不幸的是,在執行Iterator特徵時,這在Rust中是不可能的 - 不允許修改與該方法的原始特徵定義相比的生命期關係。

好消息是,最近合併的generic associated type RFC將在編譯器中實現時提供語言功能。可能需要一些時間。

我已經試過最近實現類似的功能自己,最簡單的方法,我已經與現有的穩定的編譯器發現是要求Clone + Iterator,從「主機」迭代器(https://gitlab.com/mihails.strasuns/example-iterators-calendar/blob/master/src/split_adaptor.rs

分別迭代分割塊