rustHow to iterate in pairs in Rust
Iterating in pairs in Rust can be done using the .zip()
method. This method takes two iterators and returns a new iterator of pairs. The following example code will print out the pairs of numbers from two separate vectors:
let v1 = vec![1, 2, 3];
let v2 = vec![4, 5, 6];
for (a, b) in v1.iter().zip(v2.iter()) {
println!("{} {}", a, b);
}
Output example
1 4
2 5
3 6
Code explanation
let v1 = vec![1, 2, 3];
: creates a vectorv1
with the elements1, 2, 3
let v2 = vec![4, 5, 6];
: creates a vectorv2
with the elements4, 5, 6
for (a, b) in v1.iter().zip(v2.iter())
: creates a loop that iterates over the pairs of elements fromv1
andv2
println!("{} {}", a, b);
: prints out the elements of each pair
Helpful links
Related
- Rust for loop range inclusive example
- How to iterate lines in file in Rust
- How to iterate string lines in Rust
- How to loop until error in Rust
- How to iterate linked list in Rust
- How to sleep in a loop in Rust
- How to iterate a map in Rust
- How to iterate hashset in Rust
- How to iterate hashmap in loop in Rust
More of Rust
- How to convert a Rust slice to a fixed array?
- How to convert a slice of bytes to a string in Rust?
- How to match whitespace with a regex in Rust?
- How to replace strings using Rust regex?
- How to escape dots with regex in Rust?
- How to convert Rust bytes to a vector of u8?
- How to get a value by key from JSON in Rust?
- How to parse JSON string in Rust?
- How to declare a matrix in Rust?
- How to calculate the sum of a Rust slice?
See more codes...