</>
Skip to content
Go lessons (28/34)

Go — Channels

Basic channel

package main

import "fmt"

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

    go func() {
        ch <- "Hello"
    }()

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

Buffered channel

ch := make(chan int, 5)

ch <- 1
ch <- 2
ch <- 3

fmt.Println(<-ch) // 1
fmt.Println(<-ch) // 2
fmt.Println(<-ch) // 3

Range over channels

ch := make(chan int)

go func() {
    for i := 0; i < 5; i++ {
        ch <- i
    }
    close(ch)
}()

for v := range ch {
    fmt.Println(v)
}

Directional channels

// Send-only
func producer(ch chan<- int) {
    ch <- 42
}

// Receive-only
func consumer(ch <-chan int) {
    v := <-ch
    fmt.Println(v)
}

Select

ch1 := make(chan string)
ch2 := make(chan string)

go func() { ch1 <- "one" }()
go func() { ch2 <- "two" }()

select {
case msg := <-ch1:
    fmt.Println(msg)
case msg := <-ch2:
    fmt.Println(msg)
default:
    fmt.Println("No value ready")
}

Channel patterns

// Fan-out: distribute work
func fanOut(input <-chan int, workers int) []<-chan int {
    channels := make([]<-chan int, workers)
    for i := 0; i < workers; i++ {
        channels[i] = process(input)
    }
    return channels
}

// Fan-in: merge channels
func fanIn(channels ...<-chan int) <-chan int {
    var wg sync.WaitGroup
    merged := make(chan int)

    for _, ch := range channels {
        wg.Add(1)
        go func(c <-chan int) {
            defer wg.Done()
            for v := range c {
                merged <- v
            }
        }(ch)
    }

    go func() {
        wg.Wait()
        close(merged)
    }()

    return merged
}

Best practices

  • Close channels from the sender side
  • Don't send on closed channels
  • Use buffered channels when you know the size
  • Use select for non-blocking operations
  • Use directional channels for clarity

Mini Practice

Write Go code that:

  1. Creates a producer-consumer pattern with channels
  2. Uses select with a default case
  3. Ranges over a channel
  4. Implements fan-in to merge multiple channels

Up Next

Congratulations! You've completed the Go fundamentals. Continue exploring advanced topics like interfaces, packages, and the standard library.

Related Topics

Frequently Asked Questions about Channels

What is Channels in Go?

Channels is a fundamental concept in Go. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Channels?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Channels.

Why is Channels important in Go?

Channels is essential for Go development. Understanding this concept will help you write better code and solve real-world problems more effectively.