Question:
In the below code block I am trying to run several routines and get results (Whether success or error) for all of them.Answer:
Waitgroup is redundant in this code. Execution is perfectly synced with the loop that is waiting for the channel’s result. Code is not moved forward until all functions finish their work and posted results are read from the channels. Waitgroup is only necessary if your function needs to do any work AFTER results are posted to channels.I also prefer a slightly different implementation. In a posted implementation, we are not sending both results and errors into the channels every time when the function is executed. Instead, we can send only the result for successful execution and send only an error when the code fails.
The advantage is simplified results/errors processing. We are getting slices of results and errors without
nils
.In this example, the function returns a number, and we send its default value of
0
in case of error. It could be complicated to filter out not successful execution results from successful if zero could be legit function execution result.Same with errors. To check if we have any errors, we can use simple code like
if len(errs) != 0
.multierr
package. For example, github.com/hashicorp/go-multierror
.If you have better answer, please add a comment about this, thank you!