Welcome To Golang By Example

Select versus switch in Go (Golang)

Overview

Below are some of the differences between switch and select statement

switch statement; expression {
case expression1:
     //Dosomething
case expression2:
     //Dosomething
default:
     //Dosomething
}

Format of select

select {
case channel_send_or_receive:
     //Dosomething
case channel_send_or_receive:
     //Dosomething
default:
     //Dosomething
}

This is how switch works. Given a switch expression, it goes through all cases and tries to find the first case expression that matches the switch expression otherwise the default case is executed if present. The order of matching is from top to bottom. While with a select statement ,it chooses  the case on which send or receive operation on a channel  is not blocked and is ready to be executed. If multiple cases are ready to be executed then one is choosen at random.

Please refer to comprehensive tutorial for both

Example of switch

package main

import "fmt"

func main() {
    switch ch := "b"; ch {
    case "a":
        fmt.Println("a")
    case "b":
        fmt.Println("b")    
    default:
        fmt.Println("No matching character")    
    }
    
    //fmt.Println(ch)

}  

Output:

b

In the above example, the switch case goes in sequence and matches the switch expression which is “b” here.

Example of select

package main

import "fmt"

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

    go goOne(ch1)
    go goTwo(ch2)

    select {
    case msg1 := <-ch1:
        fmt.Println(msg1)
    case msg2 := <-ch2:
        fmt.Println(msg2)
    }
}
func goOne(ch chan string) {
    ch <- "From goOne goroutine"
}
func goTwo(ch chan string) {
    ch <- "From goTwo goroutine"
}

Output

From goOne goroutine

In the above program we created two channels which are passed to two different goroutines. Then each of the  goroutine  is sending one value to the channel. In the select  we have two case statement. Each of the two case statement is waiting for a receive operation to complete on one of the channels. Once any receive operation is complete on any of the channel it is executed and select exits. So as seen from output, in the above program it  prints the received value from one of the channel and exits.

So in the above program since it is not deterministic which of the send operation will complete earlier that is why you will see different output if you run the program different times.