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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With