rustHow to iterate over a Rust slice with an index?
Iterating over a Rust slice with an index can be done using a for loop. The loop will iterate over each element in the slice and provide the index of the element as well.
let my_slice = [1, 2, 3, 4];
for (index, element) in my_slice.iter().enumerate() {
println!("Element at index {} is {}", index, element);
}
Output example
Element at index 0 is 1
Element at index 1 is 2
Element at index 2 is 3
Element at index 3 is 4
Code explanation
let my_slice = [1, 2, 3, 4];: This declares a slice containing the elements 1, 2, 3, and 4.for (index, element) in my_slice.iter().enumerate(): This is theforloop which will iterate over each element in the slice. Theenumerate()method will provide the index of the element as well.println!("Element at index {} is {}", index, element);: This prints out the index and element of the current iteration.
Helpful links
Related
- Does Rust perform bounds checking on slices?
- How to create a subslice from a Rust slice?
- How to push an element to a Rust slice?
- How to convert a Rust slice of u8 to a string?
- How to convert a Rust slice of u8 to u32?
- How to calculate the sum of a Rust slice?
- How to split a Rust slice?
- How to remove elements from a Rust slice?
- How to join two Rust slices?
- How to check for equality between Rust slices?
More of Rust
- How to use regex lookahead in Rust?
- How to ignore case in Rust regex?
- How to replace a capture group using Rust regex?
- How to get all matches from a Rust regex?
- How to use regex to match a double quote in Rust?
- How to replace strings using Rust regex?
- How to make regex case insensitive in Rust?
- How to use a tuple as a key in a Rust HashMap?
- How to compare two Rust HashMaps?
- How to insert an element into a Rust HashMap if it does not already exist?
See more codes...