```go package main func main() { nums := make(chan int, 10) for i := 0; i < 10; i++ { nums <- i } close(nums) for i := 0; i < 3; i++ { go square(nums) } } func square(nums <-chan int) <-chan int { res := make(chan int, 10) for n := range nums { res <- n * n } return res } ```
sobes.tech AI
Answer from AI
The provided code has several issues related to the use of channels and goroutines:
-
The
sqarefunction (probably a typo, should besquare) takes a channelnumsas input and creates a new channelres, into which it writes the squares of the numbers. However, the function returnsres, but inmain, this returned channel is not used. -
In
main, three goroutinessqare(nums)are started, which read from the samenumschannel simultaneously. This may lead to each element being processed by only one goroutine, which might be expected. -
However, since
resis created inside each goroutine and not passed outside, the calculation results are lost.
To fix the code and get the squares of the numbers, you can do the following:
- Create a single output channel
resinmain. - Pass it to the goroutines to write results.
- In
main, read the results fromres.
Example of the corrected code:
package main
import (
"fmt"
"sync"
)
func main() {
nums := make(chan int, 10)
res := make(chan int, 10)
for i := 0; i < 10; i++ {
nums <- i
}
close(nums)
var wg sync.WaitGroup
for i := 0; i < 3; i++ {
wg.Add(1)
go func() {
defer wg.Done()
square(nums, res)
}()
}
go func() {
wg.Wait()
close(res)
}()
for val := range res {
fmt.Println(val)
}
}
func square(nums <-chan int, res chan<- int) {
for n := range nums {
res <- n * n
}
}
In this version, three goroutines read from nums in parallel, compute the square, and write to the shared res channel. After all goroutines finish, the res channel is closed, and main prints all results.