Go Channels provide a way for two goroutines to communicate with each other and synchronize their execution.
Here is an example program using channels:
package main /* www.j ava2s .co m*/ import ( "fmt" "time" ) func pinger(c chan string) { for i := 0; ; i++ { c <- "ping" } } func printer(c chan string) { for { msg := <- c fmt.Println(msg) time.Sleep(time.Second * 1) } } func main() { var c chan string = make(chan string) go pinger(c) go printer(c) var input string fmt.Scanln(&input) }
This program will print ping
forever.
hit Enter to stop it.
A channel type is represented with the keyword chan
followed by the type of the things that are passed on the channel.
The left arrow operator (<-) is used to send and receive messages on the channel.
c <- "ping" means send "ping".
msg := <- c means receive a message and store it in msg.