How do I write an iterator that returns references to itself?

前端 未结 3 965
故里飘歌
故里飘歌 2020-11-22 14:18

I am having trouble expressing the lifetime of the return value of an Iterator implementation. How can I compile this code without changing the return value of

3条回答
  •  逝去的感伤
    2020-11-22 15:06

    As far as I understand, you want want the iterator to return a vector of references into itself, right? Unfortunately, it is not possible in Rust.

    This is the trimmed down Iterator trait:

    trait Iterator {
        type Item;
        fn next(&mut self) -> Option;
    }
    

    Note that there is no lifetime connection between &mut self and Option. This means that next() method can't return references into the iterator itself. You just can't express a lifetime of the returned references. This is basically the reason that you couldn't find a way to specify the correct lifetime - it would've looked like this:

    fn next<'a>(&'a mut self) -> Option>
    

    except that this is not a valid next() method for Iterator trait.

    Such iterators (the ones which can return references into themselves) are called streaming iterators. You can find more here, here and here, if you want.

    Update. However, you can return a reference to some other structure from your iterator - that's how most of collection iterators work. It could look like this:

    pub struct PermutationIterator<'a, T> {
        vs: &'a [Vec],
        is: Vec
    }
    
    impl<'a, T> Iterator for PermutationIterator<'a, T> {
        type Item = Vec<&'a T>;
    
        fn next(&mut self) -> Option> {
            ...
        }
    }
    

    Note how lifetime 'a is now declared on impl block. It is OK to do so (required, in fact) because you need to specify the lifetime parameter on the structure. Then you can use the same 'a both in Item and in next() return type. Again, that's how most of collection iterators work.

提交回复
热议问题