Go

Channels — Basics

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Channels are typed pipes between goroutines. Unbuffered = synchronous handoff; buffered = up to N values queued. Close a channel to signal "no more values" — receivers see ok=false.
Go
Raw
package main

import "fmt"

func main() {
    // Unbuffered — send blocks until a receiver is ready
    ch := make(chan int)
    go func() {
        ch <- 42                              // blocks until main receives
    }()
    fmt.Println(<-ch)                         // 42

    // Buffered — sends only block when the buffer is full
    buf := make(chan string, 3)
    buf <- "a"
    buf <- "b"
    buf <- "c"
    close(buf)                                // signal "no more values"

    // range exits when the channel is closed AND drained
    for s := range buf {
        fmt.Println(s)
    }

    // Detect close on a per-receive basis
    done := make(chan struct{})
    close(done)
    if _, ok := <-done; !ok {
        fmt.Println("channel closed")
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.