if else Statement #
The if else statement is used to execute one block of code if a condition is true, and another block of code if the condition is false.
Syntax #
if condition {
// code to execute if condition is true
} else {
// code to execute if condition is false
}Example #
package main
import ("fmt")
func main() {
x := 20
y := 18
if x > y {
fmt.Println("x is greater than y")
} else {
fmt.Println("x is not greater than y")
}
}Example explained #
In the example above, we test if x is greater than y. Since x (20) is indeed greater than y (18), the first block executes and prints:
x is greater than yIf the condition were false, the code inside the else block would run instead.