如何在堆栈上创建按值迭代器? [英] How do I create a by-value iterator on the stack?

查看:57
本文介绍了如何在堆栈上创建按值迭代器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在堆中创建一个消耗迭代器:

I can create a consuming iterator in the heap:

vec![1, 10, 100].into_iter()

我还可以在借用元素的堆栈上创建一个迭代器:

I can also create an iterator on the stack that borrows the elements:

[1, 10, 100].iter()

但是如果我这样写:

[1, 10, 100].into_iter()

这不是一个消耗大量的迭代器,因为[T; _]::into_iter不存在:IntoIterator仅针对借用的版本(也称为切片)实现.是否有一种简单的方法(最好是在std lib中)在堆栈上创建使用迭代器?

This is not a consuming iterator because [T; _]::into_iter does not exist: IntoIterator is only implemented for the borrowed version (aka slice). Is there a simple way (preferably in the std lib) to create a consuming iterator on the stack?

我知道[1, 10, 100].iter().cloned()是可以做到的,但这要求物品是可克隆的.

I know that [1, 10, 100].iter().cloned() can be done, but this requires the items to be clonable.

推荐答案

您可以拥有一个将值包装在将它们链接在一起:

You can have a macro which wraps the values in a once iterator and chains them together:

macro_rules! value_iter {
    () => {
        std::iter::empty()
    };
    ($v: expr, $( $rest: expr ), +) => {
        std::iter::once($v).chain(
            value_iter!($($rest),*)
        )
    };
    ($v: expr) => {
        std::iter::once($v)
    };
}

使用:

#[derive(Debug, PartialEq)]
struct Foo;

let it = value_iter![Foo, Foo, Foo];

let all: Vec<_> = it.collect();
assert_eq!(all, vec![Foo, Foo, Foo]);

一个已知的缺点是迭代器将不是精确大小的迭代器,因此编译器可能会错过一些明显的优化.

A known drawback is that the iterator will not be an exact-size iterator, and so the compiler might miss some obvious optimizations.

游乐场

这篇关于如何在堆栈上创建按值迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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