Conditional branching statement in Golang
The conditional branch or branching statement is an instruction in a computer program that begin execution instruction in different order based on condition. It deviate from its default behavior which is top to bottom. The common conditional branching statements provided by Golang language includes if-else, switch.

if statement

The if statement can be used if lines of code needs to be executed only if condition is true. Otherwise control should be proceed with execution by skipping the block of code provided in if statement block.
If statement
 1 package main
 2 
 3 import "fmt"
 4 
 5 func main() {
 6 
 7 	v1, v2, v3 := 33, 54, 34
 8 
 9 	if v1 > v2 {
 10 	   fmt.Printf("A variable v1 is greater than v2")
 11 	} else if v1 > v3 { // else if condition
 12 	   fmt.Printf("A variable v1 is greater than v3")
 13 	} else {
 14 	   fmt.Printf("A variable v1 is smallest value.")
 15 	}
 16 }

Switch statement

The switch statement is branching statement which allows to execute one statement or block based on the case value or condition. It also allows to specify default case if none of the case gets executed.
Switch statement
 1 switch {
 2     case ch == 'A':
 3         fmt.Println("You have entered A !")
 4     case ch == 'E':
 5         fmt.Println("You have entered E !")
 6     case ch == 'I':
 7         fmt.Println("You have entered I !")
 8     case ch == 'O':
 9         fmt.Println("You have entered O !")
 10     case ch == 'U':
 11         fmt.Println("You have entered U !")
 12    default:
 13         fmt.Println("You have entered vowel !")
 14 }

Select statement

The select statement allows to specify or refers to communication which sent or receive operation on the channel. Select statement waits until the specified communication channel (send or receive operation) is prepared for some cases to begin.
Select statement
 1 R1 := make(chan string)
 2 R2 := make(chan string)
 3 
 4 go delayBySec(R1, 2)
 5 go delayBySec(R2, 5)
 6 
 7 select {
 8     // case 1 delay by 2
 9     case op1 := <-R1:
 10         fmt.Println(op1)
 11     
 12     // case 2 delay by 5
 13     case op2 := <-R2:
 14         fmt.Println(op2)
 15 }
Privacy Policy
Terms of Service
Disclaimer
Contact us
About us