rustHow to zip two vectors in Rust?
Zipping two vectors in Rust can be done using the zip
method. This method takes two iterators and returns a new iterator of tuples, where the first element of each tuple 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, 6];
let zipped: Vec<_> = v1.iter().zip(v2.iter()).collect();
println!("{:?}", zipped);
Output example
[(1, 4), (2, 5), (3, 6)]
Code explanation
let v1 = vec![1, 2, 3];
: creates a vectorv1
with elements1
,2
, and3
.let v2 = vec![4, 5, 6];
: creates a vectorv2
with elements4
,5
, and6
.let zipped: Vec<_> = v1.iter().zip(v2.iter()).collect();
: creates a new vectorzipped
by zippingv1
andv2
using thezip
method. Thezip
method takes two iterators and returns a new iterator of tuples, where the first element of each tuple is taken from the first iterator, and the second element is taken from the second iterator. Thecollect
method is then used to collect the iterator into a vector.println!("{:?}", zipped);
: prints the vectorzipped
to the console.
Helpful links
Related
More of Rust
- How to split a Rust slice?
- How to convert a slice to a hex string in Rust?
- How do I create a variable in Rust?
- How to get the bytes of a Rust slice?
- How to compare with null in Rust
- How to use non-capturing groups in Rust regex?
- How to ignore case in Rust regex?
- How to parse JSON string in Rust?
- How to use a custom hasher with a Rust HashMap?
- How to modify an existing entry in a Rust HashMap?
See more codes...