channel

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: May 4, 2024 License: Apache-2.0 Imports: 1 Imported by: 0

Documentation

Overview

Package channel implements an interator that reads a data stream from the supplied channel.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Iterator

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

Iterator traverses the elements of type T from a channel, until the channel is closed.

Example
package main

import (
	"context"
	"fmt"
	"math/rand"

	"github.com/jake-scott/go-functional/iter/channel"
)

func main() {
	ctx := context.Background()

	// will always return the same output
	rand := rand.New(rand.NewSource(123))

	ch := make(chan int)
	go func() {
		for i := 0; i < 10; i++ {
			r := rand.Int() % 100

			ch <- r
		}

		close(ch)
	}()

	iter := channel.New(ch)
	for iter.Next(ctx) {
		fmt.Printf("item: %d\n", iter.Get())
	}

	if err := iter.Error(); err != nil {
		panic(err)
	}

}
Output:

item: 89
item: 46
item: 43
item: 83
item: 87
item: 63
item: 48
item: 91
item: 75
item: 28

func New

func New[T any](ch chan T) Iterator[T]

New returns an implementation of Iterator that traverses the provided channel until reading the channel returns an error, or the channel is closed.

ChannelIterator does not support the SizeHint interface

func (*Iterator[T]) Error

func (i *Iterator[T]) Error() error

Error returns the context expiry reason if any from a previous call to Next, otherwise it returns nil.

func (*Iterator[T]) Get

func (i *Iterator[T]) Get() T

Get returns the value stored by the last successful Next method call, or the zero value of type T if Next has not been called.

The context is not used by this method.

func (*Iterator[T]) Next

func (i *Iterator[T]) Next(ctx context.Context) bool

Next reads an item from the channel and stores the value, which can be retrieved using the Get() method. Next returns true if an element was successfully read from the channel, or false if the channel was closed or if the context expired.

If the context expired, Err() will return the result of the context's Err() function.

Jump to

Keyboard shortcuts

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