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 replace strings using Rust regex?
- How to use captures_iter with regex in Rust?
- How to use regex to match a double quote in Rust?
- How to use regex lookbehind in Rust?
- How to convert struct to bytes in Rust
- How to use 'or' in Rust regex?
- How to insert an element into a Rust HashMap if it does not already exist?
- How to print a Rust HashMap?
- How to loop through a Rust HashMap?
- How to compare two Rust HashMaps?
See more codes...