Essential Go Concurrency  Suggest an edit

Hello World goroutine

Single channel, single goroutine, one write, one read.

func main() {
	// create new channel of type string
	ch := make(chan string)

	// start new anonymous goroutine
	go func() {
		time.Sleep(time.Second)
		// send "Hello World" to channel
		ch <- "Hello World"
	}()
	// read from channel
	msg, ok := <-ch
	fmt.Printf("msg='%s', ok='%v'\n", msg, ok)
}
msg='Hello World', ok='true'

The channel ch is an unbuffered or synchronous channel.

The time.Sleep is here to illustrate main() function will wait on the ch channel, which means the function literal executed as a goroutine has the time to send a value through that channel: the receive operator <-ch will block the execution of main().

If it didn’t, the goroutine would be killed when main() exits, and would not have time to send its value.

  ↑ ↓ to navigate     ↵ to select     Esc to close