Go else if Statement

In Go, the else if statement is used to introduce additional conditions to be evaluated after the initial condition (if) has been determined to be false. This allows for multiple levels of decision-making within your program.

Tutorials dojo strip



Syntax

The syntax for the else if statement in Go is:

if condition1 {
    // Code to execute if condition1 is true
} else if condition2 {
    // Code to execute if condition1 is false and condition2 is true
} else {
    // Code to execute if both condition1 and condition2 are false
}




Example 1: Determining Time of Day

Here’s how the else if statement can be used to determine the appropriate greeting based on the time of day.

package main
import ("fmt")

func main() {
    hour := 22
    if hour < 10 {
        fmt.Println("Good morning.")
    } else if hour < 20 {
        fmt.Println("Good day.")
    } else {
        fmt.Println("Good evening.")
    }
}

Result: Since the variable hour is set to 22, which is not less than 10 and not less than 20, the else block is executed, printing “Good evening.”




Example 2: Comparing Motorcycle Speeds

Let’s use motorcycle brands for a fun example. Here, we compare the speeds of different motorcycles.

package main
import ("fmt")

func main() {
    ducatiSpeed := 140
    yamahaSpeed := 120
    hondaSpeed := 140

    if ducatiSpeed > yamahaSpeed {
        fmt.Println("Ducati is faster than Yamaha.")
    } else if ducatiSpeed > hondaSpeed {
        fmt.Println("Ducati is faster than Honda.")
    } else {
        fmt.Println("Ducati is tied with Honda.")
    }
}

Explanation of Example 2

In this example:

  • Three variables (ducatiSpeed, yamahaSpeed, and hondaSpeed) represent the speeds of motorcycles.
  • The first condition checks whether Ducati’s speed is greater than Yamaha’s.
  • If false, the else if statement evaluates whether Ducati’s speed is greater than Honda’s.
  • If both conditions are false, the else block executes, indicating that Ducati and Honda have the same speed.

Result: Since ducatiSpeed and hondaSpeed are both 140, the program prints “Ducati is tied with Honda.”




Important Behavior of else if

If multiple conditions in the if and else if statements are true, only the first true condition is executed. For example:

package main
import ("fmt")

func main() {
    suzukiRating := 30
    if suzukiRating >= 10 {
        fmt.Println("Suzuki's rating is 10 or higher.")
    } else if suzukiRating > 20 {
        fmt.Println("Suzuki's rating is above 20.")
    } else {
        fmt.Println("Suzuki's rating is below 10.")
    }
}

Result: Since suzukiRating is 30, the condition suzukiRating >= 10 is true, so the first block executes, and the program prints “Suzuki’s rating is 10 or higher.” The subsequent conditions are not evaluated.

Tutorials dojo strip
Scroll to Top