rustHow to zip arrays in Rust?
Zipping two arrays in Rust can be done using the zip
method from the Iterator
trait. 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 a = [1, 2, 3];
let b = [4, 5, 6];
let zipped = a.iter().zip(b.iter());
for t in zipped {
println!("{:?}", t);
}
Output example
(1, 4)
(2, 5)
(3, 6)
Code explanation
let a = [1, 2, 3];
: creates an arraya
with elements1
,2
, and3
.let b = [4, 5, 6];
: creates an arrayb
with elements4
,5
, and6
.let zipped = a.iter().zip(b.iter());
: creates a new iteratorzipped
by zipping the iterators ofa
andb
.for t in zipped {
: iterates over the tuples inzipped
.println!("{:?}", t);
: prints the tuplet
in a debug format.
Helpful links
Related
More of Rust
- How to match whitespace with a regex in Rust?
- How to use non-capturing groups in Rust regex?
- How to use regex lookbehind in Rust?
- How to use the global flag in a Rust regex?
- How to use regex to match a double quote in Rust?
- How to match the end of a line in a Rust regex?
- How to create a new Rust HashMap with values?
- How to get the length of a Rust HashMap?
- How to split a string by regex in Rust?
- How to use a tuple as a key in a Rust HashMap?
See more codes...