user19018
user19018

Reputation: 2489

How can I push an iterator to an existing vector (or any other collection)?

Looking through the documentation or Rust 0.12, I saw the following method to push multiple values to an already existing Vec:

fn push_all(&mut self, other: &[T])

However, if I have an iterator, I don't think it is efficient to use: vector.push_all(it.collect().as_ref()). Is there a more efficient way?

Upvotes: 32

Views: 17715

Answers (1)

fjh
fjh

Reputation: 13081

You can use Vec's extend method. extend takes a value of any type that implements IntoIterator (which includes all iterator types) and extends the Vec by all elements returned from the iterator:

vector.extend(it)

Since extend belongs to the Extend trait, it also works for many other collection types.

Upvotes: 55

Related Questions