If Else Statements in Go Programming Language
If Statement
If statement is used to execute a block of code when the specified condition evaluates to true.
Syntax
if condition{
//executable statemnets
}
Example
package main
import "fmt"
func main() {
age:=18
if age >= 17 && age <= 30 {
fmt.Println("My SecondAge is between 17 and 30")
}
}
You can run this program live here https://onecompiler.com/go/3usgmwf33
Output
My Age is between 17 and 30
If-else Statement
If-else Statement allows you to execute block of code if the condition evaluates to true and another block will execute if it is evaluates to false.
Syntax
if condition{
//code needs to be executed if it is True
}else{
//code needs to be executed if it is false
}
Example
package main
import (
"fmt"
)
func main() {
number := 10
if number%2 == 0 {
fmt.Println(number,":is an even number")
} else {
fmt.Println(number," :is an odd number")
}
}
You can run this program live here https://onecompiler.com/go/3ut3r69dg
Output
10 : is an even number
If...else if...else Statement
If allows us to combine multiple if...else statements.
Syntax
if condition-1 {
// code needs to be executed if condition-1 is true
} else if condition-2 {
// code needs to be executed if condition-2 is true
} else {
// code needs to be executed if both condition1 and condition2 are false
}
Example
package main
import ("fmt")
func main() {
var BMI = 21.0
if BMI < 18.5 {
fmt.Println("You are underweight");
} else if BMI >= 18.5 && BMI < 25.0 {
fmt.Println("Your weight is normal");
} else if BMI >= 25.0 && BMI < 30.0 {
fmt.Println("You're overweight")
} else {
fmt.Println("You're obese")
}
}
You can run this program live here https://onecompiler.com/go/3ut3ygzs2
Output
Your weight is normal
Initialization in If-Statement
In Golang If-Statement supports composite syntax where condition precedes initialization.
Syntax
if vardeclaration; condition{
//code needs to be executed if condition is True
}
Example
package main
import "fmt"
func main() {
if number := 10 ; number%2 == 0{
fmt.Println(number,": is even")
}else{
fmt.Println(number,": is Odd")
}
}
You can run this program live here https://onecompiler.com/go/3ut3z4f86
Output
10 : is even