Sobes.tech
Junior — Middle

How can it be determined that all channels are closed from the Main method?

sobes.tech AI

Answer from AI

In Go, determining that all channels are closed from the main method can be done in several ways, depending on the context:

  1. Use a channel for signaling completion — for example, closing a separate channel when all worker goroutines have finished.

  2. Check for channel closure during read — when reading from a channel, the operator v, ok := <-ch returns ok == false if the channel is closed and all data has been read.

  3. Use sync.WaitGroup to wait for all goroutines that write to the channel to finish, and then close the channel in main after they complete.

Example with WaitGroup:

var wg sync.WaitGroup
ch := make(chan int)

wg.Add(1)
go func() {
    defer wg.Done()
    // work with the channel
    ch <- 1
}()

// In a separate goroutine, close the channel after all senders are done
ngo func() {
    wg.Wait()
    close(ch)
}()

for v := range ch {
    fmt.Println(v) // loop ends when the channel is closed
}

Thus, in main, you can determine that the channel is closed when the loop over it ends, which indicates that all data has been sent and the channel is closed.