The else if Statement
When the first condition turns out false, an else if statement lets you test another one.
Else If Statement Syntax
main.go
if condition1 {
// code to be executed if condition1 is true
} else if condition2 {
// code to be executed if condition1 is false and condition2 is true
} else {
// code to be executed if condition1 and condition2 are both false
}
Using The else if Statement
The programs in this section put else if to work.
Example
With time at 22, the first condition (below 10) is false. The else if test (below 20) fails too. Since condition1 and condition2 have both failed, only the else block is left, and it prints "Good evening."
Prompt
Use else if to check time of day and print a greeting.
Set time to 22.
Output: Go program and captured output
main.go
package main
import ("fmt")
func main() {
time := 22
if time < 10 {
fmt.Println("Good morning.")
} else if time < 20 {
fmt.Println("Good day.")
} else {
fmt.Println("Good evening.")
}
}
Example
Here else if helps compare a and b. Both hold 14, so neither test passes and the else block reports that they are equal.
Prompt
Use else if to compare two equal variables and print the result.
Set both a and b to 14.
Output: Go program and captured output
main.go
package main
import ("fmt")
func main() {
a := 14
b := 14
if a < b {
fmt.Println("a is less than b.")
} else if a > b {
fmt.Println("a is more than b.")
} else {
fmt.Println("a and b are equal.")
}
}
Example
Note: Go stops at the first condition that passes. With x at 30, condition1 and condition2 would both pass, yet only the code for condition1 runs:
Prompt
Show that when both condition1 and condition2 are true, only the code for condition1 runs.
Set x to 30 and test with >= 10 and > 20.
Output: Go program and captured output
main.go
package main
import ("fmt")
func main() {
x := 30
if x >= 10 {
fmt.Println("x is larger than or equal to 10.")
} else if x > 20 {
fmt.Println("x is larger than 20.")
} else {
fmt.Println("x is less than 10.")
}
}