[英]Take an `Iterator` instead of `Vec` when possible?
When a function takes a series of values as a parameter, is it considered good style to accept an Iterator<T>
instead of Vec<T>
? 当函数将一系列值作为参数时,接受
Iterator<T>
而不是Vec<T>
是否被认为是好的风格?
This way, the caller can decide on their own how the series is stored (inside a Vec
, a [T; N]
or anything else, actually an Option<T>
should be possible!). 这样,调用者可以自己决定如何存储序列(在
Vec
内部, [T; N]
或其他任何内容,实际上Option<T>
应该是可能的!)。 Also, this eliminates the need to convert the whatever you have into a Vec
, and also, after applying some Iterator modifiers, no .collect()
is needed! 此外,这消除了将所有内容转换为
Vec
,并且在应用一些Iterator修饰符后,不需要.collect()
! So it should also be faster! 所以它也应该更快!
Am I missing something or is this the way it should be done? 我错过了什么或这是应该做的方式吗?
Such a function as you describe should typically generically take an IntoIterator<Item = T>
; 你描述的这样一个函数通常应该通常使用
IntoIterator<Item = T>
; thus it can accept both Iterator<T>
and Vec<T>
as input. 因此它可以接受
Iterator<T>
和Vec<T>
作为输入。
This can be combined with other techniques, too; 这也可以与其他技术结合使用; for example, this method
concat
will accept a &[&str]
(and thus &Vec<&str>
by auto deref/ref coercion), &[String]
(and thus &Vec<String>
), a &str
iterator, a String
iterator, et cetera : 例如,这个方法
concat
将接受一个&[&str]
(因此&Vec<&str>
vec &Vec<&str>
通过auto deref / ref强制), &[String]
(以及&Vec<String>
),一个&str
迭代器,一个String
迭代器, 等等。 cetera :
use std::borrow::Borrow;
fn concat<T: Borrow<str>, Iter: IntoIterator<Item = T>>(iter: Iter) -> String {
iter.into_iter() // -> impl Iterator<Item = T>
.map(|s| s.borrow()) // -> impl Iterator<Item = &str>
.collect() // -> String
}
(This specific example would actually typically be better suited to SliceConcatExt
, because it's able to calculate how long the final result will be up front and thus allocate the right length string all at once. But it's just a proof of the concept and how multiple fancy techniques can be combined.) (这个具体的例子实际上通常更适合
SliceConcatExt
,因为它能够计算最终结果预先存在的时间,从而一次性分配正确的长度字符串。但它只是概念的证明以及多个花哨技术可以结合起来。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.