search

What is the difference between Go's select statements and switch statements?

While both select and switch are control flow statements in Go, they have different purposes and syntax.

A **switch** statement is used to execute different code blocks depending on the value of a given expression. It allows you to test a value against multiple cases, and execute the code block corresponding to the first matching case. Here is an example:

func main() {
    switch day := "Monday"; day {
    case "Monday":
        fmt.Println("Today is Monday")
    case "Tuesday":
        fmt.Println("Today is Tuesday")
    default:
        fmt.Println("Today is some other day")
    }
}

In contrast, a **select** statement is used to wait on multiple communication operations, such as sending or receiving on channels. It allows you to wait until one of the communication operations is ready to proceed, and then execute the code block corresponding to that operation. Here is an example:

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

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

    select {
    case msg1 := <-ch1:
        fmt.Println(msg1)
    case msg2 := <-ch2:
        fmt.Println(msg2)
    }
}

In this example, the **select** statement waits until one of the channels **ch1** and **ch2** is ready to receive a value, and then prints the received value. If both channels are ready, it chooses one of them randomly.

Related Questions You Might Be Interested