How do I concatenate two slices in Rust?

前端 未结 3 748
不思量自难忘°
不思量自难忘° 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:33

    Ok, first of all, your initial sequence definition is wrong. You say you want 1, 2, 3, 8, 9, 10 as output, so it should look like:

        let v = (1u64 .. 11).collect::>();
    

    Next, you say you want to concatenate slices, so let's actually use slices:

        let head = &v[..3];
        let tail = &v[l-3..];
    

    At this point, it's really down to which approach you like the most. You can turn those slices into iterators, chain, then collect...

        let v2: Vec<_> = head.iter().chain(tail.iter()).collect();
    

    ...or make a vec and extend it with the slices directly...

        let mut v3 = vec![];
        v3.extend_from_slice(head);
        v3.extend_from_slice(tail);
    

    ...or extend using more general iterators (which will become equivalent in the future with specialisation, but I don't believe it's as efficient just yet)...

        let mut v4: Vec = vec![];
        v4.extend(head);
        v4.extend(tail);
    

    ...or you could use Vec::with_capacity and push in a loop, or do the chained iterator thing, but using extend... but I have to stop at some point.

    Full example code:

    fn main() {
        let v = (1u64 .. 11).collect::>();
        let l = v.len();
    
        let head = &v[..3];
        let tail = &v[l-3..];
    
        println!("head: {:?}", head);
        println!("tail: {:?}", tail);
    
        let v2: Vec<_> = head.iter().chain(tail.iter()).collect();
        println!("v2: {:?}", v2);
    
        let mut v3 = vec![];
        v3.extend_from_slice(head);
        v3.extend_from_slice(tail);
        println!("v3: {:?}", v3);
    
        // Explicit type to help inference.
        let mut v4: Vec = vec![];
        v4.extend(head);
        v4.extend(tail);
        println!("v4: {:?}", v4);
    }
    

提交回复
热议问题