Ir al contenido

Range Over Channel Without Close (ARCH5036)

Esta página aún no está disponible en tu idioma.

Key go.async.range-chan-no-close · Severity warning · Category async

Ranging over a channel that is never closed anywhere in the package leaves the range loop blocked forever after the last value. The producer side must close the channel once it is done sending.

func Sum(nums []int) int {
ch := make(chan int)
go func() {
for _, n := range nums {
ch <- n
}
// missing close
}()
total := 0
for v := range ch { // blocks after the last value
total += v
}
return total
}
func Sum(nums []int) int {
ch := make(chan int)
go func() {
for _, n := range nums {
ch <- n
}
close(ch)
}()
total := 0
for v := range ch {
total += v
}
return total
}

Close the channel with close(ch) once the producing goroutine is done sending.