如何将迭代器推送到现有向量(或任何其他集合)?
How can I push an iterator to an existing vector (or any other collection)?
查看文档或 Rust 0.12,我看到 the following method 将多个值推送到已经存在的 Vec
:
fn push_all(&mut self, other: &[T])
但是,如果我有一个迭代器,我认为使用效率不高:vector.push_all(it.collect().as_ref())
。有没有更有效的方法?
您可以使用 Vec
的 extend
method。 extend
接受实现 IntoIterator
的任何类型的值(包括所有迭代器类型)并通过从迭代器返回的所有元素扩展 Vec
:
vector.extend(it)
由于 extend
属于 Extend
特征,它也适用于许多其他集合类型。
查看文档或 Rust 0.12,我看到 the following method 将多个值推送到已经存在的 Vec
:
fn push_all(&mut self, other: &[T])
但是,如果我有一个迭代器,我认为使用效率不高:vector.push_all(it.collect().as_ref())
。有没有更有效的方法?
您可以使用 Vec
的 extend
method。 extend
接受实现 IntoIterator
的任何类型的值(包括所有迭代器类型)并通过从迭代器返回的所有元素扩展 Vec
:
vector.extend(it)
由于 extend
属于 Extend
特征,它也适用于许多其他集合类型。