Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between switch and select in Go?

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

like image 204
Thomas Avatar asked Aug 08 '16 04:08

Thomas


People also ask

What is select used for in Golang?

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.

What is type switch in Golang?

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.

How does switch case work in Golang?

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.

Does go have a switch statement?

Go language supports two types of switch statements: Expression Switch. Type Switch.


1 Answers

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." 
like image 76
null Avatar answered Sep 22 '22 23:09

null