In this section, we are going to see how to select the results of concurrent rank functions as they are returned. Consider that we have two Go routines in our main
function that are basically setting their own channels: channel1
and channel2
. Let's say that we want to read whatever comes first and then continue to the next line. For this, Go provides a built-in construct that is called select
, and select
basically waits for a channel to be filled and looks like a switch
statement. So, let's go ahead and see what that looks like now:
package main import ( "time" "fmt" ) func main() { channel1 := make(chan string) channel2 := make(chan string) go func(){ time.Sleep(1*time.Second) channel1 <- "Hello from channel1" }() go func(){ time.Sleep(1 * time.Second) channel2 <- "Hello from channel2" }() var result string select { case result = <-channel1: fmt.Println(result) case result = <-channel2:...