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

前端 未结 2 1096
鱼传尺愫
鱼传尺愫 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 07:59

    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.

提交回复
热议问题