Best way to concatenate vectors in Rust

前端 未结 3 755
渐次进展
渐次进展 2020-12-01 09:55

Is it even possible to concatenate vectors in Rust? If so, is there an elegant way to do so? I have something like this:

let mut a = vec![1, 2, 3];
let b = v         


        
3条回答
  •  [愿得一人]
    2020-12-01 10:38

    The structure std::vec::Vec has method append():

    fn append(&mut self, other: &mut Vec)
    

    Moves all the elements of other into Self, leaving other empty.

    From your example, the following code will concatenate two vectors by mutating a and b:

    fn main() {
        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, []);
    }
    

    Alternatively, you can use Extend::extend() to append all elements of something that can be turned into an iterator (like Vec) to a given vector:

    let mut a = vec![1, 2, 3];
    let b = vec![4, 5, 6];
    
    a.extend(b);
    assert_eq!(a, [1, 2, 3, 4, 5, 6]);
    // b is moved and can't be used anymore
    

    Note that the vector b is moved instead of emptied. If your vectors contain elements that implement Copy, you can pass an immutable reference to one vector to extend() instead in order to avoid the move. In that case the vector b is not changed:

    let mut a = vec![1, 2, 3];
    let b = vec![4, 5, 6];
    
    a.extend(&b);
    assert_eq!(a, [1, 2, 3, 4, 5, 6]);
    assert_eq!(b, [4, 5, 6]);
    

提交回复
热议问题