go channel select

tags: learning go programming

content

  • when a thread is listening multiple channels, it can use select to await these channels
    • when it comes to select, think of it as waiting
func main() {
	ch1 := make(chan int)
	ch2 := make(chan int)
	go func(ch chan int) {ch <- 1}(ch1)
	go func(ch chan int) {ch <- 2}(ch2)
	for range 2 {
		select {
		case msg := <-ch1:
			fmt.Println("received from channel 1:", msg)
		case msg2 := <-ch2:
			fmt.Println("received from channel 2:", msg2)
		}
	}
}

up

go-channel-basics

down

go-select-and-switch go-select-syntax

reference