rustHow to zip vectors of different lengths in Rust?
Zipping vectors of different lengths in Rust can be done using the zip
method from the Iterator
trait. This method takes two iterators and returns a new iterator of pairs, where the first element of each pair is taken from the first iterator, and the second element is taken from the second iterator.
Example code
let v1 = vec![1, 2, 3];
let v2 = vec![4, 5];
let zipped: Vec<_> = v1.iter().zip(v2.iter()).collect();
println!("{:?}", zipped);
Output example
[(1, 4), (2, 5)]
Code explanation
let v1 = vec![1, 2, 3];
: creates a vectorv1
with elements1
,2
, and3
.let v2 = vec![4, 5];
: creates a vectorv2
with elements4
and5
.let zipped: Vec<_> = v1.iter().zip(v2.iter()).collect();
: creates a new vectorzipped
by zipping the two vectorsv1
andv2
using thezip
method from theIterator
trait. Thezip
method takes two iterators and returns a new iterator of pairs, where the first element of each pair is taken from the first iterator, and the second element is taken from the second iterator.println!("{:?}", zipped);
: prints the vectorzipped
to the console.
Helpful links
Related
More of Rust
- How to modify an existing entry in a Rust HashMap?
- How to declare a matrix in Rust?
- Hashshet example in Rust
- How to parse JSON string in Rust?
- How to use a custom hash function with a Rust HashMap?
- How to yield return in Rust?
- How to convert a Rust slice of u8 to u32?
- How to convert a Rust slice to a fixed array?
- Yield example in Rust
- How to build a Rust HashMap from an iterator?
See more codes...