Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

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 like:

trait IterShort<Iter>
    where Self: Borrow<Iter>,
{
    type Item;

    fn next(self) -> Option<Self::Item>;
}

then an implementation could look like:

impl<'a, MyIter> IterShort<MyIter> for &'a mut MyIter {
    type Item = &'a mut MyItem;

    fn next(self) -> Option<Self::Item> {
        // ...
    }
}

I realize I could write my own (I just did), but I'd like one that works with the for-loop notation. Is that possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The standard iterators can't do this as far as I can see. The very definition of an iterator is that the outside has control over the elements while the inside has control over what produces the elements.

From what I understand of what you are trying to do, I'd flip the concept around and instead of returning elements from an iterator to a surrounding environment, pass the environment to the iterator. That is, you create a struct with a constructor function that accepts a closure and implements the iterator trait. On each call to next, the passed-in closure is called with the next element and the return value of that closure or modifications thereof are returned as the current element. That way, next can handle the lifetime of whatever would otherwise be returned to the surrounding environment.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...