Skip to content
Go

select

Multiplex channels using select.

By EZ4Code Team
selectchannel

Code

package main

import (
    "fmt"
    "time"
)

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

    go func() {
        time.Sleep(1 * time.Second)
        ch1 <- "one"
    }()
    go func() {
        time.Sleep(2 * time.Second)
        ch2 <- "two"
    }()

    for i := 0; i < 2; i++ {
        select {
        case msg1 := <-ch1:
            fmt.Println("received", msg1)
        case msg2 := <-ch2:
            fmt.Println("received", msg2)
        case <-time.After(3 * time.Second):
            fmt.Println("timeout")
        }
    }
}

Explanation

select listens on multiple channels simultaneously, executing the branch of whichever is ready first.

More Go Snippets