Go Channels

Hello World of Go Channels

The power of using go routines comes from being able to communicate via channels, aka message passing. Here is a dead simple example of its use.

  1. We create a channel and specify the type for it. In this case a string so we can return a message to the caller as a string. This can be any type , including Structs
var c chan string = make(chan string)`
  1. Next we use the go keyword to launch our background/async function and pass the channel to it.

func doThis(c chan string) {
  time.Sleep(1 * time.Second)
  fmt.Println("Finished the long operation in 'doThis'")
  c <- "`doThis` is done"
}

The interesting part is in the last line when the function is done we send a string message to the channel using the directional operator: <-

  1. The caller (in our case main()) reads from the channel and blocks until a output is received:
  x := <- c
  1. Once the signal from the channel is recieved the caller can continue.

Full Listing

Here is the full listing followed by the output of running it:

package main

import (
	"fmt"
	"time"
)

func doThis(c chan string) {
	time.Sleep(1 * time.Second)
	fmt.Println("Finished the long operation in 'doThis'")
	c <- "`doThis` is done"
}
func main() {
	var c chan string = make(chan string)
	go doThis(c)
	fmt.Println("Kicked off the go routine")

	x := <-c
	fmt.Println("Message from channel: ", x)
}
Kicked off the go routine
Finished the long operation in 'doThis'
Message from channel:  `doThis` is done

253 Words

2019-09-12 10:20 -0400