Iterators in Rust

I found an interesting article about iterators in Rust (in German). It has been a while since I found some time to try some Rust and I decided to try some of the examples in the article.

The following code block show a very simple example of how to use iterators.

pub fn run_iterator() {
    let numbers = &vec![1, 1, 2, 3, 5, 8, 13];

    println!("The min is {}", numbers.into_iter().min().unwrap());

    for number in numbers {
        println!("The next value is {}", number);
    }
}

By the way, I which that WordPress had syntax highlighting for Rust code blocks. 🙁

Anyway, I have learned that memory ownership is important here and that the above code would not work, if I had written let numbers = vec![1, 1, 2, 3, 5, 8, 13] instead of let numbers = &vec![1, 1, 2, 3, 5, 8, 13]. Note the added ampersand sign (&), which denotes a borrowed reference.

It looks like I have to learn more about memory ownership in Rust before working with iterators. 🙂

Source code for this blog post can be found on SourceForge.

Referenced article: Ferris Talk #1: Iteratoren in Rust (in German). Copyright © 2021 Heise Medien.

Comment