是否存在类似迭代器的特征,它返回必须在下一次访问之前超出范围的引用? [英] Is there an Iterator-like trait which returns references that must fall out of scope before the next access?

查看:12
本文介绍了是否存在类似迭代器的特征,它返回必须在下一次访问之前超出范围的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可以安全地迭代同一个元素两次,或者为项目类型中被迭代的全局事物保持某种状态.

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.

类似:

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> {
        // ...
    }
}

我意识到我可以自己编写(我刚刚做到了),但我想要一个与 for 循环符号一起使用的.这可能吗?

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?

推荐答案

据我所知,标准迭代器无法做到这一点.迭代器的真正定义是外部控制元素,而内部控制生成元素的内容.

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.

根据我对您正在尝试做的事情的理解,我会颠倒这个概念,而不是将元素从迭代器返回到周围环境,而是将环境传递给迭代器.也就是说,您创建一个带有构造函数的结构,该构造函数接受闭包并实现迭代器特征.在每次调用 next 时,传入的闭包与下一个元素一起调用,并且该闭包的返回值或其修改作为当前元素返回.这样,next 可以处理任何会返回到周围环境的生命周期.

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.

这篇关于是否存在类似迭代器的特征,它返回必须在下一次访问之前超出范围的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆