else if Statement

The else if Statement #

Use the else if statement to specify a new condition if the first condition is false.

Syntax #

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
}

Example 1: Using time #

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.")
  }
}

Result:

Good evening.

Example explained #

In the example above:

  • time is 22, which is greater than 10 → first condition is false.
  • time < 20 → second condition is false.
  • Since both are false, the else block executes, printing “Good evening”.

If time was 14, the program would print “Good day.”

Example 2: Comparing two numbers #

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.")
  }
}

Result:

a and b are equal.

Note #

If condition1 and condition2 are both true, only the code for condition1 executes:

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.")
  }
}

Result:

x is larger than or equal to 10.