From the course: Go Practice: Functions

Unlock this course with a free trial

Join today to access over 25,300 courses taught by industry experts.

Solution: Goroutines

Solution: Goroutines - Go Tutorial

From the course: Go Practice: Functions

Solution: Goroutines

- [Instructor] I've opted to change the implementation of the previous challenge. In this case, this has saved me time, but it can sometimes be easier to write concurrent code from scratch instead of modifying existing code. On line 24, I've created a results channel inside the scope of the sum function. It's initialized as a buffer channel, which allocates the same capacity for saving results as the numbers slice. This will allow our goroutines to immediately write the results without being blocked. Next, on lines 26 to 28, I created a goroutine which takes a single int parameter, I. This parameter is a placeholder for the number I'm currently processing. Inside the goroutine on line 27, I send the function return value to the results channel. Finally, I invoke the anonymous function with the num variable as a parameter. While the goroutine does have access to the num variable in the for loop, this number will…

Contents