Sobes.tech
Junior — Senior

Eliminate panic when attempting to write to a closed channel

livecode

Task condition

In this example, the program crashes with a panic: send on closed channel, because the main goroutine closes the channel ch without waiting for the goroutine, which is trying to write to the channel at that time. It is necessary to change the behavior so that the program terminates correctly, for example, by waiting for the goroutine to finish before closing the channel.

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)
}