if else statement in Golang
The if-else statement can be used when either of the block needs to be execute by the control. If the condition is true, it will executes if block otherwise execute fallback statements or else block. It will execute either of the block.
if-else statement
 1 // if else statement
 2 if(condition) {
 3     // statements if condition true
 4 } else {
 5     // fallback statements
 6 }
if-else statement
 1 package main
 2 
 3 import "fmt"
 4 
 5 func main() {
 6 
 7 	a, b, c := 20, 10, 30
 8 
 9 	if a > b {
 10 	   fmt.Printf("Value of a is greater than b")
 11 	} else {
 12 	   fmt.Printf("Value of a is not greater than b")
 13 	}
 14 
 15 	if a > c {
 16 	   fmt.Printf("\nValue of a is greater than c")
 17 	} else {
 18 	   fmt.Printf("\nValue of a is not greater than c")
 19 	}
 20 }
In the above example, we have define three variables and initialize with value 20, 10, 30 respectively. The first if statement, compare with a and b and print if block print statement as a is greater than b. The second if statement, compare with a and c and print else block print statement as a is less than c.
Output
 1 Value of a is greater than b
 2 Value of a is not greater than c

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 	a, b := 20, 10
 8 
 9 	if a > b {
 10 	   fmt.Printf("Value of a is greater than b")
 11 	}
 12 }

else-if statement

The else-if can be used to validate more than one condition with the given variable value but either one can be execute at a time. The else-if statement can be used only with If statement, where else-if is optional. If statement can be exist without else-if or else.
else-if statement
 1 package main
 2 
 3 import "fmt"
 4 
 5 func main() {
 6 
 7 	a, b, c := 10, 50, 10
 8 
 9 	if a > b && a > c {
 10 	   fmt.Printf("variable a is greater than b and c")
 11 	} else if b > a && b > c { // else if condition
 12 	   fmt.Printf("variable b is greater than a and c")
 13 	} else {
 14 	   fmt.Printf("variable c is greater than a and b")
 15 	}
 16 }
Privacy Policy
Terms of Service
Disclaimer
Contact us
About us