Iterators

1-minute read

Iterators are functions with a special signature:


func (yield func(V) bool)

Iterators yield one value at a time, allowing us to range over a queue of values instead of getting all values all at once.

package main

import "fmt"

type Int struct {
	Val     int
	Visible bool
}

type Ints []Int

func (ii Ints) All(yield func(Int) bool) {
	for _, n := range ii {
		if !yield(n) {
			return
		}
	}
}

func main() {
	ints := Ints{
		{1, true},
		{2, false},
		{3, true},
	}

	for n := range ints.All {
		fmt.Println(n)
	}
}
iterators.go
Copy

Support us via BuyMeACoffee

Resources

Here are some resources we recommend for you to use along with this lesson: