Is there an Iterator-like trait which returns references that must fall out of scope before the next access?

前端 未结 2 1098
鱼传尺愫
鱼传尺愫 2020-12-21 07:35

This would make it possible to safely iterate over the same element twice, or to hold some state for the global thing being iterated over in the item type.

Something

2条回答
  •  再見小時候
    2020-12-21 08:11

    The std::iter::Iterator trait can not do this, but you can write a different trait:

    trait StreamingIterator {
        type Item;
        fn next<'a>(&'a mut self) -> Option<&'a mut Self::Item>;
    }
    

    Note that the return value of next borrows the iterator itself, whereas in Vec::iter for example it only borrows the vector.

    The downside is that &mut is hard-coded. Making it generic would require higher-kinded types (so that StreamingIterator::Item could itself be generic over a lifetime parameter).

    Alexis Beingessner gave a talk about this and more titled Who Owns This Stream of Data? at RustCamp.

    As to for loops, they’re really tied to std::iter::IntoIterator which is tied to std::iter::Iterator. You’d just have to implement both.

提交回复
热议问题