Range Over Channel Without Close (ARCH5036)
Dieser Inhalt ist noch nicht in deiner Sprache verfügbar.
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.
Incorrect
Section titled “Incorrect”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}Correct
Section titled “Correct”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.