here's a find_smallest function, but when i use while let, it whould never return. once i use for loop,it will works well.
pub fn find_smallest(v: &[i32]) -> Option<usize> {
if v.is_empty() {
return None;
}
let mut smallest = &v[0];
let mut ans = None;
//this will never return
// while let Some((index, current)) = v.iter().enumerate().next() {
// if current < smallest {
// smallest = current;
// ans = Some(index);
// }
// }
//but this works well
for (i, n) in v.iter().enumerate() {
if n < smallest {
smallest = n;
ans = Some(i)
}
}
ans
}
You're creating a new iterator at the beginning of every loop, which always gives you the first item in the slice. For it to work, you need to create an iterator once, outside of the loop, like this:
let mut iterator = v.iter().enumerate()
while let Some((index, current)) = iterator.next() {
if current < smallest {
smallest = current;
ans = Some(index);
}
}