Collecting iterator into existing vec


#1
  1. I think there’s a one line solution. I have checked the Iterator / Vec documentation, but can not find which function to use.

  2. I have the following:




pub fn foo() {
    let input = vec![1_i32, 2, 3];
    let output = vec![1_i32, 2, 4];

    let t: Vec<i32> = input.iter().map(|x| x + 1).collect();
}
  1. What happens here is that the mapped results are dumped into a new vector t … what I want is for the iterator results to be appended to the end of “output”. Is there a way to “collect into an existing vector”?

#2

You can use the extend method on the Vec.

It comes from this trait
https://doc.rust-lang.org/std/iter/trait.Extend.html


#3
let mut output = vec![1_i32, 2, 4];
output.extend(input.iter().map(|x| x + 1));

#4

@vitalyd , @KrishnaSannasi :

extend solved it. thanks!