Skip to content

Commit

Permalink
Make the Go function generic in its return type.
Browse files Browse the repository at this point in the history
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).
  • Loading branch information
creachadair committed Oct 29, 2023
1 parent 7bc62a1 commit 1fd3d46
Showing 1 changed file with 7 additions and 10 deletions.
17 changes: 7 additions & 10 deletions single.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down

0 comments on commit 1fd3d46

Please sign in to comment.