frankban / iterate

Iterators and lazy evaluation using generics

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

GoDoc Build Status

iterate

go get github.com/frankban/iterate

Iterators and lazy evaluation in Go. This package uses generics, so requires Go 1.18 at least.

For a complete API reference, see the package documentation.

All functions work with implementations of the Iterator interface.

// Iterator is implemented by types producing values of type T.
type Iterator[T any] interface {
	// Next advances the iterator. The next value can be then retrieved using
	// the Value method. False is returned when the iteration is done. Further
	// calls to Next should just return false with no other side effects. When
	// iterating produces an error, false is returned, and Err() returns the
	// error.
	Next() bool

	// Value returns the most recent value generated by a call to Next. It may
	// be called any number of times between calls to Next. If called after Next
	// has returned false, it returns the zero value.
	Value() T

	// Err returns the first error occurred while iterating.
	Err() error
}

Implementations are typically used in for loops, for instance:

    for iterator.Next() {
        v := iterator.Value()
        // Do something with v.
    }
    if err := iterator.Err(); err != nil {
        // Handle error.
    }

Depending on the implementation, producing values might lead to errors. For this reason it is important to always check Err() after iterating.

About

Iterators and lazy evaluation using generics

License:MIT License


Languages

Language:Go 100.0%