switch is used to make decisions based on the value of a variable of any type. Read more:
The Go switch is more general than C. The expressions do not have to be constants or even integers, cases are evaluated from top to bottom until a match is found, and if the switch has no expression, it turns on true. Therefore, it is possible - and idiomatically - to write an if-else-if-else chain as a switch.
Example usage: ( Go Playground )
package main import ( "fmt" "runtime" ) func main() { fmt.Print("Go runs on ") switch os := runtime.GOOS; os { case "darwin": fmt.Println("OS X.") case "linux": fmt.Println("Linux.") default:
The select statement allows goroutine to wait for several communication operations.
Selects blocks until one of his cases can be started, then he executes this case. He chooses one randomly, if several are ready. Here is one example: ( Go Playground )
package main import ( "fmt" "time" ) func main() { tick := time.Tick(100 * time.Millisecond) boom := time.After(500 * time.Millisecond) for { select { case <-tick: fmt.Println("tick.") case <-boom: fmt.Println("BOOM!") return default: fmt.Println(" .") time.Sleep(50 * time.Millisecond) } } }
Mayank patel
source share