What is the difference between switch and select in Go?

Thomas picture Thomas · Aug 8, 2016 · Viewed 18.6k times · Source

Is there any difference between switch and select in Go,
apart from the fact that one takes an argument and the other not?

Answer

null picture null · Aug 8, 2016

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."