Sobes.tech
Middle+

package main import ( "fmt" "time" ) func main() { ch := make(chan int) go func() { ch <- 1 }() time.Sleep(time.Millisecond * 500) close(ch) for i := range ch { fmt.Println(i) } time.Sleep(time.Millisecond * 100) }

sobes.tech AI

Answer from AI

In this code, a channel ch of type chan int is created, then a goroutine is started that sends the value 1 into the channel. After a 500-millisecond pause, the channel is closed.

Feature: the for i := range ch loop reads from the channel until it is closed. In this case, since only one value is sent to the channel and it is closed afterward, the loop will output 1.

If you remove the time.Sleep before close(ch), there is a risk that the channel will close before the goroutine sends the value, which will cause a panic when trying to send to a closed channel.

Example output:

1

Thus, the code demonstrates correct use of a channel with sending, closing, and reading via range.