在 Rust 中重用迭代器的最有效方法是什么? [英] What's the most efficient way to reuse an iterator in Rust?

查看:23
本文介绍了在 Rust 中重用迭代器的最有效方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想重用我制作的迭代器,以避免付费从头开始重新创建它.但是迭代器似乎不能 clone 并且 collect 移动了迭代器,所以我不能重用它.

I'd like to reuse an iterator I made, so as to avoid paying to recreate it from scratch. But iterators don't seem to be cloneable and collect moves the iterator so I can't reuse it.

这或多或少相当于我正在尝试做的事情.

Here's more or less the equivalent of what I'm trying to do.

let my_iter = my_string.unwrap_or("A").chars().flat_map(|c|c.to_uppercase()).map(|c| Tag::from(c).unwrap() );
let my_struct = {
  one: my_iter.collect(),
  two: my_iter.map(|c|{(c,Vec::new())}).collect(),
  three: my_iter.filter_map(|c|if c.predicate(){Some(c)}else{None}).collect(),
  four: my_iter.map(|c|{(c,1.0/my_float)}).collect(),
  five: my_iter.map(|c|(c,arg_time.unwrap_or(time::now()))).collect(),
  //etc...
}

推荐答案

如果迭代器的所有片段"都是 Clone-able,则迭代器通常是 Clone-able.my_iter 中有几个不是:匿名闭包(如 flat_map 中的闭包)和 ToUppercase 结构体.

Iterators in general are Clone-able if all their "pieces" are Clone-able. You have a couple of them in my_iter that are not: the anonymous closures (like the one in flat_map) and the ToUppercase struct returned by to_uppercase.

你可以做的是:

  1. 重建整个事物(正如@ArtemGr 建议的那样).您可以使用宏来避免重复.有点难看,但应该可以.
  2. 在填充 my_struct 之前将 my_iter 收集到 Vec 中(因为您似乎无论如何都在其中收集它):let my_iter: Vec;= my_string.unwrap_or("A").chars().flat_map(|c|c.to_uppercase()).map(|c| Tag::from(c).unwrap()).collect();
  3. 创建您自己的自定义迭代器.没有您对 my_string 的定义(因为您在其上调用 unwrap_or 我认为它不是 String)和 Tag 它是很难更具体地帮助您.
  1. rebuild the whole thing (as @ArtemGr suggests). You could use a macro to avoid repetition. A bit ugly but should work.
  2. collect my_iter into a Vec before populating my_struct (since you seem to collect it anyway in there): let my_iter: Vec<char> = my_string.unwrap_or("A").chars().flat_map(|c|c.to_uppercase()).map(|c| Tag::from(c).unwrap() ).collect();
  3. create your own custom iterator. Without your definitions of my_string (since you call unwrap_or on it I assume it's not a String) and Tag it's hard to help you more concretely with this.

这篇关于在 Rust 中重用迭代器的最有效方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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