rustHow to do a for loop with index in Rust
A for loop with index in Rust can be used to iterate over a collection of items and access the index of each item. The enumerate() method can be used to get the index of each item in the collection.
Example code
let v = vec![10, 20, 30];
for (index, value) in v.iter().enumerate() {
println!("Index: {}, Value: {}", index, value);
}
Output example
Index: 0, Value: 10
Index: 1, Value: 20
Index: 2, Value: 30
Code explanation
let v = vec![10, 20, 30];: This line creates a vectorvwith three elements.for (index, value) in v.iter().enumerate(): This line starts aforloop that iterates over the vectorvand assigns the index of each item to the variableindexand the value of each item to the variablevalue.println!("Index: {}, Value: {}", index, value);: This line prints the index and value of each item in the vector.
Helpful links
Related
More of Rust
- How to use binary regex in Rust?
- How to match a URL with a regex in Rust?
- How to ignore case in Rust regex?
- How to use regex to match a double quote in Rust?
- How to use Unicode in a regex in Rust?
- How to replace a capture group using Rust regex?
- How to split a string with Rust regex?
- How to parse a file with Rust regex?
- Regex example to match multiline string in Rust?
- How to use negation in Rust regex?
See more codes...