iter

package
v0.0.0-...-734b89f Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 24, 2022 License: Apache-2.0 Imports: 2 Imported by: 0

Documentation

Overview

Package iter provides a generic Iterator pattern, which is reduced to a minimum. This package is questionable and should be replaced until a stdlib contract approaches.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	Done = errors.New("no more items")
)

Functions

func Collect

func Collect[T any](it Iterator[T]) ([]T, error)

Collect loops the iterator and collects all items into a slice.

func Walk

func Walk[T any](it Iterator[T], f func(item T) error) error

Walk applies a closure loop to the given iterator. The Iterator is closed if possible, if the closure returns an error early.

Types

type Iterator

type Iterator[T any] interface {
	// Next returns the next result. Returns Done if there are no more results. A return of Done is idempotent
	// and multiple calls have no effect.
	// See usage example.
	Next() (T, error)
}

Iterator defines the minimal contract for an Iterator pattern. Implementations must deallocate or close any open resource (e.g. file or network) on the first returned error. If not all entries are consumed, underlying finalizers will clean any open file descriptors, however implementations may provide an optional io.Closer for immediate release.

Example (Next)
package main

import (
	"fmt"
	"github.com/golangee/repository/iter"
)

func main() {
	var it iter.Iterator[string]
	for {
		item, err := it.Next()
		if err == iter.Done {
			break
		}

		if err != nil {
			// TODO: Handle error.
		}

		fmt.Println(item)
	}
}
Output:

Example (Next2)
package main

import (
	"fmt"
	"github.com/golangee/repository/iter"
)

func main() {
	var it iter.Iterator[string]
	for item, err := it.Next(); err != iter.Done; {

		if err != nil {
			// TODO: Handle error.
		}

		fmt.Println(item)
	}
}
Output:

func Iter

func Iter[T any](slice []T) Iterator[T]

Iter wraps a slice into an iterator.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL