47. Go - Channel Ranges
Can iterate over channel values from buffer list.
close()
// Closes the channel so channel does not expect any more values. still can read, but not receive.
// Should close a channel before ranging over it to avoid deadlock error.
Example:
package main
import "fmt"
func main() {
channelOne := make(chan int)
go func() {
for i := 0; i < 50; i++ {
channelOne <- i
}
close(channelOne)
}()
for i := range channelOne {
fmt.Println(i)
}
}
// using for range to iterate over a channel until it is closed.
// it keeps pulling values from the channel until the channel is closed, then range loop ends.
// channel is finally closed in the goroutine func after the 50 loop.
Comments
Post a Comment