Sometimes you need to check multiple conditions, not just two. The else if statement allows you to chain multiple conditions together, creating more complex decision-making logic.
The else if statement sits between if and else, allowing you to test additional conditions when the first one is false.
score := 85
if score >= 90 {
fmt.Println("Grade: A")
} else if score >= 80 {
fmt.Println("Grade: B")
} else if score >= 70 {
fmt.Println("Grade: C")
} else {
fmt.Println("Grade: F")
}
// Output: Grade: B
This is crucial: Go evaluates conditions from top to bottom and stops at the first one that's true. This means the order of your conditions is very important.
value := 150
// WRONG - will never reach the second condition
if value > 50 {
fmt.Println("Greater than 50")
} else if value > 100 {
fmt.Println("Greater than 100") // Never executes!
}
// CORRECT - check larger values first
if value > 100 {
fmt.Println("Greater than 100") // This executes
} else if value > 50 {
fmt.Println("Greater than 50")
}
In the wrong example, even though 150 is greater than 100, the first condition (value > 50) is true, so it executes that block and skips the rest. Always put your most specific or largest conditions first!
You can chain as many else if statements as you need.
age := 25
if age < 13 {
fmt.Println("Child")
} else if age < 18 {
fmt.Println("Teenager")
} else if age < 65 {
fmt.Println("Adult")
} else {
fmt.Println("Senior")
}
// Output: Adult
Now let's make the checkPowerLevel function more interesting by adding multiple power level tiers.
Modify the function to handle three cases (be careful about the order!):
powerLevel is greater than 9000, print "It's over 9000!!!"powerLevel is greater than 1000000, print "Godlike!!!"powerLevel is less than or equal to 9000), print "Meh, it's only " followed by the power level valueThe function signature remains the same:
func checkPowerLevel(powerLevel int) {
// Your code here
}