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 match whitespace with a regex in Rust?
- How to replace a capture group using Rust regex?
- How to replace all using regex in Rust?
- How to replace all matches using Rust regex?
- How to borrow from vector in Rust
- How to split a string with Rust regex?
- How to match a URL with a regex in Rust?
- How to use non-capturing groups in Rust regex?
- How to parse a file with Rust regex?
- How to get a capture group using Rust regex?
See more codes...