Skip to main content

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

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

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