Sobes.tech
Junior — Middle

How can data reading from a channel be terminated in programming?

sobes.tech AI

Answer from AI

In Go, to finish reading from a channel, it is common to close the channel using the close() function. When the channel is closed, attempting to read from it returns the zero value and false as the second parameter, which allows detecting the end of data.

Example:

ch := make(chan int)
go func() {
    for i := 0; i < 5; i++ {
        ch <- i
    }
    close(ch) // signal that there is no more data
}()

for val := range ch {
    fmt.Println(val) // reads until the channel is closed
}

In this example, the for val := range ch loop will automatically end when the channel is closed and all data has been read.

How can data reading from a channel be terminated in… - sobes.tech