Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 345
user19018 Avatar asked May 29 '15 22:05

user19018


1 Answers

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.

like image 157
fjh Avatar answered Oct 31 '22 04:10

fjh