iterator

package module
v0.0.0-...-640983d Latest Latest
Warning

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

Go to latest
Published: Feb 26, 2024 License: MIT Imports: 1 Imported by: 0

README

Iterator

Go Iterator Implementation with support for Generics (requires Go v1.18+).

Issues Stars License Stars Issues Twitter

Quickstart

package main

import (
	"fmt"

	"github.com/felix-kaestner/iterator"
)

func main() {
	s := []int{1, 2, 3}
	i := iterator.FromSlice(s)

	for i.HasNext() {
		item, _ := i.Next()
		fmt.Println(fmt.Sprintf("item: %d", *item))
	}
}

Output:

item: 1
item: 2
item: 3

Installation

Install with the go get command:

$ go get -u github.com/felix-kaestner/iterator

Contribute

All contributions in any form are welcome! 🙌🏻
Just use the Issue and Pull Request templates and I'll be happy to review your suggestions. 👍


Released under the MIT License.

Documentation

Index

Constants

This section is empty.

Variables

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

Done is returned when an iterator is read past its end.

Functions

func ForEach

func ForEach[T any](iterator Iterator[T], visitor func(item *T))

ForEach iterates over the elements of the iterator, calling the provided function for each element.

This is equivalent to calling Next() until HasNext() returns false.

var it Iterator[T]
for it.HasNext() {
	v, _ := it.Next()
}

Types

type IndexedValue

type IndexedValue[T any] struct {
	// contains filtered or unexported fields
}

IndexedValue represents a value from a collection or sequence, along with its associated index in that collection or sequence.

type Iterator

type Iterator[T any] interface {
	// Next returns the next item in the iteration.
	// It returns a nil pointer and ErrIteratorOverread
	// if the iterator was read past its end.
	// Otherwise it returns a reference to the next item.
	Next() (*T, error)
	// HasNext returns true if the iteration has more elements.
	HasNext() bool
}

Iterator is the interface that allows to sequentially access the elements of a collection or another entity that can be represented as a sequence of elements.

func FromChannel

func FromChannel[T any](ch <-chan T) Iterator[T]

FromChannel returns a new Iterator for the given channel.

func FromFunc

func FromFunc[T any](fn func() (*T, error)) Iterator[T]

FromFunc returns a new Iterator for the given function.

func FromSlice

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

FromSlice returns a new Iterator for the given slice.

func WithIndex

func WithIndex[T any](iter Iterator[T]) Iterator[IndexedValue[T]]

WithIndex returns a new Iterator that wraps each element produced by the original iterator into an IndexedValue containing the index of that element and the element itself.

Jump to

Keyboard shortcuts

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