How do I concatenate two slices in Rust?

前端 未结 3 753
不思量自难忘°
不思量自难忘° 2021-02-18 21:50

I want to take the x first and last elements from a vector and concatenate them. I have the following code:

fn main() {
    let v = (0u64 .. 10).collect::

        
3条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-18 22:27

    Just use .concat() on a slice of slices:

    fn main() {
        let v = (0u64 .. 10).collect::>();
        let l = v.len();
        let first_and_last = [&v[..3], &v[l - 3..]].concat();
        println!("{:?}", first_and_last);
        // The output is `[0, 1, 2, 7, 8, 9]`
    }
    

    This creates a new vector, and it works with arbitrary number of slices.

    (Playground link)

提交回复
热议问题