Go

select — Multiplex Channel Operations

admin by @admin ADMIN
5d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`select` is like a switch for channels — runs whichever case is ready. Use `default` for non-blocking sends/receives; `case <-time.After(d)` for timeouts.
Go
Raw
package main

import (
    "fmt"
    "time"
)

func main() {
    ch1 := make(chan string)
    ch2 := make(chan string)

    go func() { time.Sleep(100 * time.Millisecond); ch1 <- "from ch1" }()
    go func() { time.Sleep(200 * time.Millisecond); ch2 <- "from ch2" }()

    for i := 0; i < 2; i++ {
        select {
        case msg := <-ch1:
            fmt.Println(msg)
        case msg := <-ch2:
            fmt.Println(msg)
        case <-time.After(500 * time.Millisecond):
            fmt.Println("timeout")
            return
        }
    }

    // Non-blocking send/recv with default
    quick := make(chan int, 1)
    select {
    case quick <- 1:
        fmt.Println("sent")
    default:
        fmt.Println("channel full, skipped")
    }
}
Tags

Save your own code snippets

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