From 1fd3d46bde13e8f8ed98637e4a7d68fe5f9bd156 Mon Sep 17 00:00:00 2001 From: "M. J. Fromberger" Date: Sun, 29 Oct 2023 11:44:46 -0700 Subject: [PATCH] Make the Go function generic in its return type. This makes no functional difference for existing use, it only allows the top-level Go function be used on types other than error. Use this to simplify the definition of Call (again, no functional change). --- single.go | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/single.go b/single.go index b92b8e2..286e0e9 100644 --- a/single.go +++ b/single.go @@ -22,24 +22,21 @@ func (s *Single[T]) Wait() T { // Go runs task in a new goroutine. The caller must call Wait to wait for the // task to return and collect its error. -func Go(task Task) *Single[error] { +func Go[T any](task func() T) *Single[T] { // N.B. This is closed by Wait. - errc := make(chan error, 1) - go func() { errc <- task() }() + valc := make(chan T, 1) + go func() { valc <- task() }() - return &Single[error]{valc: errc} + return &Single[T]{valc: valc} } // Call starts task in a new goroutine. The caller must call Wait to wait for // the task to return and collect its result. func Call[T any](task func() (T, error)) *Single[Result[T]] { - // N.B. This is closed by Wait. - valc := make(chan Result[T], 1) - go func() { + return Go(func() Result[T] { v, err := task() - valc <- Result[T]{Value: v, Err: err} - }() - return &Single[Result[T]]{valc: valc} + return Result[T]{Value: v, Err: err} + }) } // A Result is a pair of an arbitrary value and an error.