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
- How to convert a Rust slice to a fixed array?
- How to calculate the sum of a Rust slice?
- How to map a Rust slice?
- How to push an element to a Rust slice?
- How to convert a u8 slice to a hex string in Rust?
- How to remove the last element of a Rust slice?
- How to split a Rust slice?
- How to reverse a Rust slice?
- How to convert a u8 slice to hex 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 use regex to match a double quote in Rust?
- How do I print a variable in Rust?
- How to use regex lookbehind in Rust?
- How to create a Rust regex from a string?
- How to use regex to match a group in Rust?
- How to perform matrix operations in Rust?
- How to compare two HashSets in Rust?
- How to use Unicode in a regex in Rust?
See more codes...