What are channels used for?

chan is a channel in Golang. In simple word you can think it as a box in which you put a item at one end and then pick it from other end.

Unbuffered Channels

enter image description here

Buffered Channel

enter image description here

This is the small code I have written for you to understand channels. Now change order of go routines and see the outputs. Each time output may differ.

    package main

    import (
        "fmt"
        "time"
    )

    func main() {
        messages := make(chan int)
        go func() {
            time.Sleep(time.Second * 3)
            messages <- 1
        }()
        go func() {
            time.Sleep(time.Second * 2)
            messages <- 2
        }() 
        go func() {
            time.Sleep(time.Second * 1)
            messages <- 3
        }()
        go func() {
            for i := range messages {
                fmt.Println(i)
            }
        }()
        go func() {
            time.Sleep(time.Second * 1)
            messages <- 4
        }()
        go func() {
            time.Sleep(time.Second * 1)
            messages <- 5
        }()
        time.Sleep(time.Second * 5)
    }

For best understanding visit this blog where go routines and channels are described in GUI.

Visit http://divan.github.io/posts/go_concurrency_visualize/

Leave a Comment