chanx

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Jun 17, 2026 License: MIT Imports: 2 Imported by: 0

Documentation

Overview

Package chanx provides utilities for working with channels in Go, including type conversions and concurrency patterns.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FanIn

func FanIn[T any](ctx context.Context, chans ...<-chan T) <-chan T

FanIn merges multiple input channels into a single output channel. It reads concurrently from each input channel and forwards values to the output. The output channel is closed when all input channels are closed or the context is canceled. This is a non-blocking, concurrent fan-in implementation that respects context cancellation.

The order of values in the output is not guaranteed, as it depends on the race between goroutines.

Example usage:

func main() {
	ctx := context.Background()
	chans := make([]chan int, 100)

	for i := 0; i < numChans; i++ {
		chans[i] = make(chan int)
		go func(chInx int) {
			defer close(chans[chInx])

			for j := 1; j <= 100; j++ {
				chans[chInx] <- j
			}
		}(i)
	}

	sum := 0
	out := chanx.FanIn[int](ctx, chanx.ToRecvChans[int](chans)...)
	for v := range out {
		sum += v
	}
	fmt.Println(sum)
}

func ToRecvChans

func ToRecvChans[T any](in []chan T) []<-chan T

ToRecvChans converts a slice of bidirectional channels to a slice of receive-only channels. This ensures that the channels can only be used for receiving values, preventing accidental sends. The function creates a new slice with the same length and copies the references.

Example:

chans := []chan int{make(chan int), make(chan int)}
recvChans := ToRecvChans(chans)

Now recvChans can be passed to functions expecting []<-chan int.

Complexity:

time: O(n)
mem: O(n)

func ToSendChans

func ToSendChans[T any](in []chan T) []chan<- T

ToSendChans converts a slice of bidirectional channels to a slice of send-only channels. This ensures that the channels can only be used for sending values, preventing accidental receives. The function creates a new slice with the same length and copies the references.

Example:

	chans := []chan string{make(chan string), make(chan string)}
	sendChans := ToSendChans(chans)

 Now sendChans can be passed to functions expecting []chan<- string.

Complexity:

time: O(n)
mem: O(n)

Types

This section is empty.

Jump to

Keyboard shortcuts

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