Created
February 9, 2023 11:41
-
-
Save cnnrrss/5addd01996ad2fafdc604d80388120e4 to your computer and use it in GitHub Desktop.
1 buffered chan errgroup result handling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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