Go else if Statement
The else if Statement
Use theelse if statement to specify a new condition if the first condition isfalse.
Syntax
// code to be executed if condition1 is true
} else ifcondition2 {
// 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
Example
This example shows how to use anelse if statement.
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.")
}
}
Result:
Good evening.Example explained
In the example above, time (22) is greater than 10, so thefirst condition isfalse. The next condition, in theelse if statement, is alsofalse, so we move on toelse condition sincecondition1 andcondition2 are bothfalse - and print to the screen "Good evening".
However, if the time was 14, our program would print "Good day."
Example
Another example for the use ofelse if.
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.")
}
}
Result:
a and b are equal.Example
Note: If condition1 and condition2 are BOTH true, only the code for condition1 are executed:
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.")
}
}
Result:
x is larger than or equal to 10.
