In Go, the else if statement is used to evaluate multiple conditions in a sequence and execute the block of code associated with the first condition that is true. It allows you to handle multiple scenarios and make decisions based on different conditions. Here’s the syntax of the else if statement in 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 all conditions are false
}
Here are a few examples of using the else if statement in Go:
- Checking the grade based on a score:
score := 80
if score >= 90 {
fmt.Println("A")
} else if score >= 80 {
fmt.Println("B")
} else if score >= 70 {
fmt.Println("C")
} else if score >= 60 {
fmt.Println("D")
} else {
fmt.Println("F")
}
- Checking the time of the day and greeting accordingly:
hour := 14
if hour < 12 {
fmt.Println("Good morning!")
} else if hour < 18 {
fmt.Println("Good afternoon!")
} else {
fmt.Println("Good evening!")
}
- Checking if a number is positive, negative, or zero:
num := -5
if num > 0 {
fmt.Println("The number is positive")
} else if num < 0 {
fmt.Println("The number is negative")
} else {
fmt.Println("The number is zero")
}
The else if statement allows you to handle multiple conditions and choose the appropriate code block based on the first condition that evaluates to true. It provides a way to create more complex decision-making structures in your Go programs.