go-infinity-channel
is a Go package that provides an infinitely queueing channel. This package offers a Channel
struct, which uses generics to hold data of any type in a queue between an input channel and an output channel. The buffer between the input and output channels queues the incoming data without any limit, making it available for the output channel. This package is useful when there's no need for buffer size constraints or when avoiding blocking during data transfers.
Try this on go playground!
package main
import (
"fmt"
"time"
infinity "github.com/Code-Hex/go-infinity-channel"
)
func main() {
ch := infinity.NewChannel[int]()
go func() {
for i := 0; i < 10; i++ {
ch.In() <- i
time.Sleep(100 * time.Millisecond)
}
ch.Close()
}()
for i := range ch.Out() {
fmt.Println("Received:", i)
}
}
Go 1.18 or later.
$ go get github.com/Code-Hex/go-infinity-channel
When reading values from the output channel, it is important to use the for range
loop to avoid panics caused by receiving from a closed channel. Do not use an incremental for
loop to read a fixed number of items from the output channel, as it may lead to panics if you try to read more items than were sent to the input channel.
Recommended:
for item := range ch.Out() {
fmt.Println(item)
}
Not recommended:
// Assuming `count` is the number of items you expect to read from the channel
for i := 0; i < count; i++ {
fmt.Println(<-ch.Out())
}