Skip to content

Instantly share code, notes, and snippets.

@cnnrrss
Created February 9, 2023 11:41
Show Gist options
  • Save cnnrrss/5addd01996ad2fafdc604d80388120e4 to your computer and use it in GitHub Desktop.
Save cnnrrss/5addd01996ad2fafdc604d80388120e4 to your computer and use it in GitHub Desktop.
1 buffered chan errgroup result handling
package main
import (
"context"
"fmt"
"golang.org/x/sync/errgroup"
)
func race(ctx context.Context) ([]int, error) {
res := make(chan []int, 1)
res <- nil
g, ctx := errgroup.WithContext(ctx)
for i := 0; i < 10; i++ {
j := i
g.Go(func() error {
res <- append(<-res, j)
return nil
})
}
err := g.Wait()
return <-res, err
}
func main() {
res, err := race(context.Background())
if err != nil {
fmt.Println(err)
return
}
fmt.Println(res)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment