How to Concatenate Vectors in Rust

Created
Modified

Using append Method

The method append() moves all the elements of other into Self, leaving other empty. See the following example:

fn main() {
  let mut a = vec![1, 2];
  let mut b = vec![3, 4];

  a.append(&mut b);
  println!("{:?}", a);
}
[1, 2, 3, 4]

Using extend Method

You can use extend() to extend a collection with the contents of an iterator:

fn main() {
  let mut a = vec![1, 2];
  let b = vec![3, 4];

  a.extend(b);
  println!("{:?}", a);
}
[1, 2, 3, 4]

Related Tags