I've got a list of elements: [1, 2, 3, 4, 5, 6]. I want to convert it into [(1, 2), (3, 4), (5, 6)].
How can I achieve this?
To convert the given list into the format given use this :
fn main() {
let original_list = vec![1, 2, 3, 4, 5, 6];
let result_list: Vec<(i32, i32)> = original_list
.chunks(2)
.filter(|chunk| chunk.len() == 2)
.map(|chunk| (chunk[0], chunk[1]))
.collect();
println!("{:?}", result_list); // [(1, 2), (3, 4), (5, 6)]
}
However do note that the code above will require a even number of elements in the list , else the 'extra' element will be ignored
Here is a solution that does not depend on chunks
fn main() {
let arr = vec![1, 2, 3, 4, 5, 6,7];
let out : Vec<_> =
(1..arr.len()).step_by(2).map(|i| {
(arr[i-1], arr[i])
}).collect();
println!("{:?}", out);
}
However whats the difference , as both output the same thing (even with odd numbers)
There's no functional difference but indexing in a loop is less idiomatic, since it incurs extra runtime checks and makes the code more complex for no benefit (given that there's now iterators and indexing).
However, I'd just use chunks_exact
instead.
Thanks for clarifying the reason , between the 2 methods. I didn't even know the chunk_exact
method even existed. Looks like rust has tons of unknown yet really useful functions built-in in the standard library
The most direct way is https://docs.rs/itertools/latest/itertools/trait.Itertools.html#method.tuples from the itertools
crate, which turns an iterator of T
into an iterator of tuples of T
.
I was under the impression chunks was not stable rust. I stand corrected.