From 0f9d8fb102d243fa6dcf4a46f2a22cd8ef18ae96 Mon Sep 17 00:00:00 2001 From: "sashakoshka@tebibyte.media" Date: Wed, 4 Dec 2024 20:00:19 -0500 Subject: [PATCH] sync: Select, Combine work with more channel types --- sync/select.go | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/sync/select.go b/sync/select.go index eb0c8d1..e90987a 100644 --- a/sync/select.go +++ b/sync/select.go @@ -4,9 +4,15 @@ import "slices" import "context" import "reflect" +// ChannelRecv is a type constraint that includes all channel types that can be +// recieved from. +type ChannelRecv[T any] interface { + ~chan T | ~<- chan T +} + // A type-safe wrapper around reflect.Select. Taken from: // https://stackoverflow.com/questions/19992334 -func Select[T any] (ctx context.Context, channels ...chan T) (int, T, bool) { +func Select[T any, C ChannelRecv[T]] (ctx context.Context, channels ...C) (int, T, bool) { var zero T // add all channels as select cases @@ -39,11 +45,12 @@ func Select[T any] (ctx context.Context, channels ...chan T) (int, T, bool) { return chosen, ret, true } return chosen, zero, false + } // Combine returns a channel that continuously returns the result of the select // until all input sources are exhauste, or the context is canceled. -func Combine[T any] (ctx context.Context, channels ...chan T) <- chan T { +func Combine[T any, C ChannelRecv[T]] (ctx context.Context, channels ...C) <- chan T { channel := make(chan T) // our silly slection routine go func () {