Skip to content

Instantly share code, notes, and snippets.

@ScMofeoluwa
Created July 13, 2024 19:54
Show Gist options
  • Save ScMofeoluwa/313ab9c2d198cd4cbce8ebd32f7265b7 to your computer and use it in GitHub Desktop.
Save ScMofeoluwa/313ab9c2d198cd4cbce8ebd32f7265b7 to your computer and use it in GitHub Desktop.
//ErrorGroup vs WaitGroup
//Gist for an article for my portfolio
//WaitGroup Approach
func checkOne(n int) error {
if n != 1 {
return errors.New("number not one")
}
return nil
}
func main() {
numbers := []int{1, 1, 1, 5}
var wg sync.WaitGroup
// create channel to handle errors
errChan := make(chan error, 1)
for _, number := range numbers {
number := number
wg.Add(1)
go func() {
defer wg.Done()
err := checkOne(number)
if err != nil {
// send error through the channel
errChan <- err
return
}
}()
}
go func() {
wg.Wait()
// close channel after all goroutines are done
close(errChan)
}()
// read channel to get the error
err := <-errChan
if err != nil {
fmt.Println(err.Error())
}
}
//ErrorGroup Approach
func checkOne(n int) error {
if n != 1 {
return errors.New("number not one")
}
return nil
}
func main() {
numbers := []int{1, 1, 1, 5}
// create new error group
eg := new(errgroup.Group)
for _, number := range numbers {
number := number
eg.Go(func() error {
return checkOne(number)
})
}
if err := eg.Wait(); err != nil {
fmt.Println(err.Error())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment