CyberSpy

Rantings from a guy with way too much free time

Channel Your Inner Gopher

2017-12-13 Programming Rob Baruch

Channeling your Inner Gopher - (Literally) Reflecting upon Channels

Many gophers are likely familiar with the communication paradigm, channels. An elegant solution to communicate (uni or bidirectionally) typed information among go-routines. In it’s simplest form, we declare as type-valued channel variable, make it, and then send and receive data through it. Easy enough!

package main

import (
        "fmt"
)

func main() {
        var simpleChan chan int = make(chan int)

        go func(c chan int) {
                // send important data to the channel
                c <- 42
                close(c)
        }(simpleChan)

        // receive data
        num := <-simpleChan
        fmt.Printf("got %d\n", num)

}

In our trivial example above, we create an chan int typed-channel and initialize it using make.

Continue reading