Sobes.tech
Junior — Middle

Kuidas toimub andmete lugemine mitmest voost või kanalist korraga?

sobes.tech AI

Vastus AI-lt

In Go, to read from multiple channels simultaneously, the select operator is used. It allows waiting for data from multiple channels and reacting to the first available.

Example:

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

go func() { ch1 <- 1 }()
go func() { ch2 <- 2 }()

select {
case val := <-ch1:
    fmt.Println("Received from ch1:", val)
case val := <-ch2:
    fmt.Println("Received from ch2:", val)
}

This way, select blocks until data appears in one of the channels, and then executes the corresponding case. This allows efficient handling of multiple data streams at the same time.