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 vectorv1with elements1,2, and3.let v2 = vec![4, 5, 6];: creates a vectorv2with elements4,5, and6.let zipped: Vec<_> = v1.iter().zip(v2.iter()).collect();: creates a new vectorzippedby zippingv1andv2using thezipmethod. Thezipmethod 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. Thecollectmethod is then used to collect the iterator into a vector.println!("{:?}", zipped);: prints the vectorzippedto the console.
Helpful links
Related
More of Rust
- How to convert Rust bytes to a struct?
- How to use Unicode in a regex in Rust?
- How to replace a capture group using Rust regex?
- How to match a URL with a regex in Rust?
- YAML serde example in Rust
- How to replace strings using Rust regex?
- How to declare a constant Rust HashMap?
- How to match whitespace with a regex in Rust?
- How to split a string with Rust regex?
- How to create a HashMap of structs in Rust?
See more codes...