Is there any difference between switch
and select
in Go,
apart from the fact that one takes an argument and the other not?
The select statement lets a goroutine wait on multiple communication operations. A select blocks until one of its cases can run, then it executes that case. It chooses one at random if multiple are ready.
A switch is a multi-way branch statement used in place of multiple if-else statements but can also be used to find out the dynamic type of an interface variable.
Switch case starts from statement condition 1, her condition will be any value which we are comparing or some string and numeric value. If condition 1 matches then it will go for the execution of statement 1 and condition 2 matches then it will go execution of statement 2 and so on it will check for each condition.
Go language supports two types of switch statements: Expression Switch. Type Switch.
A select
is only used with channels. Example
A switch
is used with concrete types. Example
A select
will choose multiple valid options at random, while aswitch
will go in sequence (and would require a fallthrough to match multiple.)
Note that a switch can also go over types for interfaces when used with the keyword .(type)
var a interface{} a = 5 switch a.(type) { case int: fmt.Println("an int.") case int32: fmt.Println("an int32.") } // in this case it will print "an int."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With