How do I concatenate two slices in Rust?

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

    You should collect() the results of the take() and extend() them with the collect()ed results of skip():

    let mut p1 = v.iter().take(3).collect::>();
    let p2 = v.iter().skip(l-3);
    
    p1.extend(p2);
    
    println!("{:?}", p1);
    

    Edit: as Neikos said, you don't even need to collect the result of skip(), since extend() accepts arguments implementing IntoIterator (which Skip does, as it is an Iterator).

    Edit 2: your numbers are a bit off, though; in order to get 1, 2, 3, 8, 9, 10 you should declare v as follows:

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

    Since the Range is left-closed and right-open.

提交回复
热议问题