DEV Community

Discussion on: Rust's Vector

Collapse
 
chayimfriedman2 profile image
Chayim Friedman • Edited

Nice article!

Two comments:

loop {
    let value = iter.next();                   // 2
    if value.is_some() {
        println!("value: {}", value.unwrap());
    } else {
        break;
    }
}
Enter fullscreen mode Exit fullscreen mode

A much better way to desugar a for loop is the following:

while let Some(value) = iter.next() {
    println!("value: {}", value);
}
Enter fullscreen mode Exit fullscreen mode

This is also more similar to how rustc desugars them.

That's actually not magic but Rust' syntactic sugar in action. for loops accept iterators. Yet, some instances can be transformed into iterators "on the fly". The type must implement the IntoIterator trait and its into_iter() function to be eligible. As seen from the diagram above, that's the case of Vec.

Actually, it's the other way around. for loops accept IntoIterators. However, every Iterator also impls IntoIterator, by this blanket impl.