This is a creation in Article, where the information may have evolved or changed.
select
And switch
is the go language in the branch operation of two ways, each has a different application scenarios.
Select
select
Can only be applied to channel operations, both for channel data reception, but also for channel data transmission.
If select
more than one branch satisfies the criteria, one of the branches that satisfies the criteria is randomly selected, as stated in the language specification:
If multiple cases can proceed, a uniform pseudo-random choice is made to decide which single communication would execute.
The expression of the ' case ' statement can be assigned a value for a variable or two variables.
There are default
statements.
The following code is an example on go by example:
12345678910111213141516171819202122232425262728 |
PackageMainImport "Time"Import "FMT"funcMain () {c1: = Make(Chan string) C2: = Make(Chan string)Go func() {time. Sleep (time. Second *1) C1 <-"One"}()Go func() {time. Sleep (time. Second *2) C2 <-"both"}() forI: =0; I <2; i++ {Select{ CaseMSG1: = <-c1:fmt. Println ("Received", MSG1) CaseMSG2: = <-c2:fmt. Println ("Received", MSG2)}}} |
Switch
switch
Branching can be done for various types, and settings can be used to determine the branch of the interface type (by I. ( Type)).
switch
The branches are executed sequentially, and this is select
different.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 |
PackageMainImport "FMT"Import "Time"funcMain () {i: =2Fmt. Print ("Write"I"as")SwitchI Case1: FMT. Println ("One") Case2: FMT. Println ("both") Case3: FMT. Println ("three") }SwitchTime. Now (). Weekday () { CaseTime. Saturday, time. Sunday:fmt. Println ("It ' s the weekend")default: FMT. Println ("It ' s a weekday")} t: = time. Now ()Switch{ CaseT.hour () < A: FMT. Println ("It ' s before noon")default: FMT. Println ("It s after noon")} Whatami: =func(IInterface{}) {SwitchT: = i. (type) { Case BOOL: FMT. Println ("I ' m a bool") Case int: FMT. Println ("I ' m an int")default: FMT. Printf ("Don ' t know type%t\n", t)}} Whatami (true) Whatami(1) Whatami ("Hey")} |