Created
July 13, 2024 19:54
-
-
Save ScMofeoluwa/313ab9c2d198cd4cbce8ebd32f7265b7 to your computer and use it in GitHub Desktop.
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
//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