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 thefor
loop 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
- How to calculate the sum of a Rust slice?
- How to get the last element of a Rust slice?
- How to convert a Rust slice to a fixed array?
- How to get the first element of a slice in Rust?
- How to swap elements in a Rust slice?
- How to check if a Rust slice contains a certain value?
- How to split a Rust slice?
- How to map a Rust slice?
- How to concatenate Rust slices?
More of Rust
- How to implement PartialEq for a Rust HashMap?
- How to use regex to match a double quote in Rust?
- How to create a Rust HashMap from a vector of tuples?
- How to calculate the sum of a Rust slice?
- How to match a URL with a regex in Rust?
- How to replace a capture group using Rust regex?
- How to replace strings using Rust regex?
- How to parse a file with Rust regex?
- How to ignore case in Rust regex?
- How to match the end of a line in a Rust regex?
See more codes...