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
- How to loop until error in Rust
- How to sleep in a loop in Rust
- How to iterate a map in Rust
- How to iterate string lines in Rust
- Rust parallel loop example
- How to iterate through hashmap keys in Rust
- How to iterate and modify a vector in Rust
- How to iterate an array with index in Rust
- How to iterate btreemap in Rust
More of Rust
- How to match whitespace with a regex in Rust?
- How to use captures_iter with regex in Rust?
- How to compile a regex in Rust?
- How to use regex to match a double quote in Rust?
- How to insert an element into a Rust HashMap if it does not already exist?
- How to use backslash in regex in Rust?
- How to use a custom hasher with a Rust HashMap?
- How to compare two Rust HashMaps?
- Yield example in Rust
- How to use the global flag in a Rust regex?
See more codes...