Starting with version 1.23, the Go programming language has added support for iterators, which lets us range over pretty much anything!
Let’s look at the List type from a previous example. In that example, we had an AllElements method that returned a slice of all elements in the list. With Go iterators, we can do it better - as shown below.
To run the program, ensure you have Rust installed and create a cargo project with this code in the main.rs file. Then run cargo run to execute it.
The expected output should be:
Packages like std::iter have a number of useful functions to work with iterators. For example, collect takes any iterator and collects all its values into a vector.
Once the loop hits break or an early return, the iterator will stop producing values.