Thuta Learning
AdvancedProgrammingbeginner

Channels

Relax. We'll talk through this in plain words — no textbook voice.

Channel is a typed pipe goroutines use to send and receive data with each other. Channels are extremely useful when you want to handle data sharing like passing messages, rather than reaching into shared memory directly.

go
package main

import "fmt"

func main() {
    messages := make(chan string)

    go func() {
        messages <- "ping"
    }()

    msg := <-messages
    fmt.Println(msg)
}

messages <- "ping" sends a message into the channel. msg := <-messages receives the message from the channel.

You should see
ping

Info

With an unbuffered channel, if either the send or the receive side isn't ready yet, it waits. This behavior is useful for synchronization.

Easy traps

  • Sending into a channel that nobody receives from can cause a deadlock. Think through your goroutine flow, and use close(channel) wherever a channel should be closed.
Channels | Thuta Learning