rustHow to map with index in Rust
Mapping with index in Rust can be done using the enumerate()
method on an iterator. This method returns a tuple of the index and the value of the element.
Example code
let v = vec![1, 2, 3];
for (i, x) in v.iter().enumerate() {
println!("Index: {}, Value: {}", i, x);
}
Output example
Index: 0, Value: 1
Index: 1, Value: 2
Index: 2, Value: 3
Code explanation
let v = vec![1, 2, 3];
: creates a vectorv
with elements1
,2
, and3
.for (i, x) in v.iter().enumerate()
: iterates over the vectorv
and assigns the indexi
and the valuex
of the element to the tuple(i, x)
.println!("Index: {}, Value: {}", i, x);
: prints the indexi
and the valuex
of the element.
Helpful links
Related
More of Rust
- How to replace a capture group using Rust regex?
- How to calculate the sum of a Rust slice?
- How do I create an array of strings in Rust?
- How to replace all matches using Rust regex?
- How to use regex to match a double quote in Rust?
- Hashshet example in Rust
- How to use regex captures in Rust?
- How to convert JSON to a struct in Rust?
- How to pop an element from a Rust HashMap?
- How to convert a Rust HashMap to a JSON string?
See more codes...