Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I concatenate two slices in Rust?

Tags:

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::<Vec<_>>();     let l = v.len();     vec![v.iter().take(3), v.iter().skip(l-3)]; } 

This gives me the error

error[E0308]: mismatched types  --> <anon>:4:28   | 4 |     vec![v.iter().take(3), v.iter().skip(l-3)];   |                            ^^^^^^^^^^^^^^^^^^ expected struct `std::iter::Take`, found struct `std::iter::Skip` <anon>:4:5: 4:48 note: in this expansion of vec! (defined in <std macros>)   |   = note: expected type `std::iter::Take<std::slice::Iter<'_, u64>>`   = note:    found type `std::iter::Skip<std::slice::Iter<'_, u64>>` 

How do I get my vec of 1, 2, 3, 8, 9, 10? I am using Rust 1.12.

like image 307
The Unfun Cat Avatar asked Oct 20 '16 12:10

The Unfun Cat


People also ask

How do you concatenate slices?

Type) []Type The append built-in function appends elements to the end of a slice. If it has sufficient capacity, the destination is resliced to accommodate the new elements. If it does not, a new underlying array will be allocated. Append returns the updated slice.

What are slices in Rust?

A slice is a pointer to a block of memory. Slices can be used to access portions of data stored in contiguous memory blocks. It can be used with data structures like arrays, vectors and strings. Slices use index numbers to access portions of data.


1 Answers

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

fn main() {     let v = (0u64 .. 10).collect::<Vec<_>>();     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)

like image 124
bluss Avatar answered Oct 31 '22 18:10

bluss