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:

Go




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.

Go

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.

Go

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:

Go

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