0

I have two slice or vectors and I want to add them, as demonstrated here in Golang:

a := []byte{1, 2, 3}
b := []byte{4, 5, 6}
ab := append(a, b...)
ba := append(b, a...)

How can I do that in Rust? I found some other questions, such as:

but, all of their best answer is a += b, and not ab = a + b.

let mut a = vec![1, 2, 3];
let mut b = vec![4, 5, 6];

a.append(&mut b);

assert_eq!(a, [1, 2, 3, 4, 5, 6]);
assert_eq!(b, []);

Or is there maybe a function like Vec::append(a, b) in Rust?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
wllenyj
  • 47
  • 1
  • 4

2 Answers2

7

You can chain your iterators:

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

    // Don't consume the original vectors and clone the items:
    let ab: Vec<_> = a.iter().chain(&b).cloned().collect();

    // Consume the original vectors. The items do not need to be cloneable:
    let ba: Vec<_> = b.into_iter().chain(a).collect();

    assert_eq!(ab, [1, 2, 3, 4, 5, 6]);
    assert_eq!(ba, [4, 5, 6, 1, 2, 3]);
}

Note that the iterator knows the number of items that it yields, so that collect can allocate directly the right amount of memory:

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

    let ba = b.into_iter().chain(a);
    assert_eq!(ba.size_hint(), (6, Some(6)));

    let ba: Vec<_> = ba.collect();
    assert_eq!(ba, [4, 5, 6, 1, 2, 3]);
}
Boiethios
  • 38,438
  • 19
  • 134
  • 183
6

There is no constructor of Vec directly appending two slices.

The functionality is not fundamental, as you can implement it yourself:

let ab = {
    let mut r = a.clone();
    r.extend_from_slice(&b);
    r
};

If you often find yourself performing this operation, you may prefer to write a function to do so:

fn cat<T: Clone>(a: &[T], b: &[T]) -> Vec<T> {
    let mut v = Vec::with_capacity(a.len() + b.len());
    v.extend_from_slice(a);
    v.extend_from_slice(b);
    v
}

And then you'll be able to do: let ab = cat(&a, &b);.

Matthieu M.
  • 287,565
  • 48
  • 449
  • 722