Since you are trying to solve the first day of Advent of Code, I'm assuming that you need to compare two consecutive characters and update an accumulator depending on whether the characters are the same. You can do that without indexing by using the fold
function on chars
. Something like this (untested):
fn example(s: &str) -> u32 {
let mut i = s.chars()
.map(|c| c.to_digit(10).expect("Invalid input: Non-digit found!"));
if let Some(first) = i.next() {
let (tot, last) = i.fold((0, first), |acc, x| {
let (tot, prev) = acc;
if prev == x {
(tot + prev, x)
} else {
(tot, x)
}
});
if last == first {
tot + last
} else {
tot
}
} else {
0
}
}
The fold
iterator method allows you to walk a value over all the iterator items updating that value at each step. Here the value is a tuple containing the accumulated result and the value of the previous digit. We initialize it with some initial result and the value of the first character. Then at each step we compare the current character with the previous one taken from the current value, update the accumulated result depending on the result of the comparison and return a new value with the updated accumulator and the current character.
The fold
method returns the last value, which in our case contains the accumulated result and the last character, at which point you may check if the last character is the same as the first one and update the result if you need to.