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 vectorvwith elements1,2, and3.for (i, x) in v.iter().enumerate(): iterates over the vectorvand assigns the indexiand the valuexof the element to the tuple(i, x).println!("Index: {}, Value: {}", i, x);: prints the indexiand the valuexof the element.
Helpful links
Related
More of Rust
- How to use regex to match a double quote in Rust?
- How to replace a capture group using Rust regex?
- Regex example to match multiline string in Rust?
- How to match the end of a line in a Rust regex?
- 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 ignore case in Rust regex?
- How to match digits with regex in Rust?
- How to use regex captures in Rust?
See more codes...