Go
channel
Communicate between goroutines using channels.
By EZ4Code Team
channelcommunication
Code
package main
import "fmt"
func main() {
ch := make(chan int, 3)
go func() {
for i := 0; i < 5; i++ {
ch <- i
}
close(ch)
}()
for v := range ch {
fmt.Println(v)
}
// Bidirectional channel
ch2 := make(chan string)
go func() { ch2 <- "hello" }()
msg := <-ch2
fmt.Println(msg)
}Explanation
Channels are pipes for goroutine communication; after close, they can be iterated with range.