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 vectorv
with three elements.for (index, value) in v.iter().enumerate()
: This line starts afor
loop that iterates over the vectorv
and assigns the index of each item to the variableindex
and 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 iterate linked list in Rust
- Rust for loop range inclusive example
- How to iterate in pairs in Rust
- How to iterate over string in Rust
- How to loop N times in Rust
- How to iterate and modify a vector in Rust
- How to iterate directory in Rust
- Rust parallel loop example
More of Rust
- How to use regex to match a group in Rust?
- How to use regex to match a double quote in Rust?
- How to parse JSON string in Rust?
- How to convert a Rust HashMap to a BTreeMap?
- How to replace strings using Rust regex?
- Regex example to match multiline string in Rust?
- How to get a capture group using Rust regex?
- How to use groups in a Rust regex?
- How to split a string by regex in Rust?
- How to convert a u8 slice to a hex string in Rust?
See more codes...