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 first element of a slice in Rust?
- How to convert a Rust slice of u8 to a string?
- How to convert a Rust slice to a fixed array?
- How to convert a slice of bytes to a string in Rust?
- How to get the last element of a slice in Rust?
- How to convert a vector to a Rust slice?
- How to convert a Rust slice to a tuple?
- How to convert a Rust slice to a string?
- How to convert a u8 slice to a hex string in Rust?
More of Rust
- How to replace a capture group using Rust regex?
- How to split a string with Rust regex?
- How to use non-capturing groups in Rust regex?
- How to match a URL with a regex in Rust?
- How to match the end of a line in a Rust regex?
- How to get an entry from a HashSet in Rust?
- How to replace all matches using Rust regex?
- How to get a capture group using Rust regex?
- How to use regex with bytes in Rust?
- How to replace all using regex in Rust?
See more codes...