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.
Just use
.concat()
on a slice of slices:This creates a new vector, and it works with arbitrary number of slices.
(Playground link)
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:Next, you say you want to concatenate slices, so let's actually use slices:
At this point, it's really down to which approach you like the most. You can turn those slices into iterators, chain, then collect...
...or make a vec and extend it with the slices directly...
...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)...
...or you could use
Vec::with_capacity
andpush
in a loop, or do the chained iterator thing, but usingextend
... but I have to stop at some point.Full example code:
You should
collect()
the results of thetake()
andextend()
them with thecollect()
ed results ofskip()
:Edit: as Neikos said, you don't even need to collect the result of
skip()
, sinceextend()
accepts arguments implementingIntoIterator
(whichSkip
does, as it is anIterator
).Edit 2: your numbers are a bit off, though; in order to get
1, 2, 3, 8, 9, 10
you should declarev
as follows:Since the
Range
is left-closed and right-open.