Junior — Middle
Kuidas saab lõpetada andmete lugemise kanalilt programmeerimises?
sobes.tech AI
Vastus AI-lt
In Go, to finish reading from a channel, the common practice is to close the channel using the close() function. When the channel is closed, attempting to read from it returns a zero value and false as the second value, 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 are 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.