Go if else Statement

In Go, the if else statement lets you specify different blocks of code to be executed based on whether a condition is true or false. This adds versatility to your programs by enabling different outcomes depending on varying conditions.

Tutorials dojo strip



Syntax

The structure of an if else statement in Go is:

Go

Key Point: Ensure that the else block starts immediately after the closing brace (}) of the if block. Otherwise, you’ll encounter a syntax error.




Example 1: Checking Time of Day

Below is an example of how if else can determine whether it’s daytime or evening.

Go

In this example, the time variable is assigned the value 20. Since 20 is not less than 18, the program skips the if block and executes the code inside the else block, printing “Good evening.”




Example 2: Motorcycle Speed Comparison

Go

Explanation of Example 2

In this example:

  • The variables hondaSpeed and suzukiSpeed represent the speeds of two motorcycles.
  • The condition checks whether Honda’s speed is greater than Suzuki’s.
  • Since 75 (Honda’s speed) is not greater than 85 (Suzuki’s speed), the code in the else block executes, printing “Suzuki is faster than Honda.”




Important Syntax Rules for the else Statement

  • The opening brace of the else block must be on the same line as the closing brace of the if block. For example: } else { // Code for the else block }
  • Placing else on a new line will result in a syntax error. For example: } else { fmt.Println("This will raise an error!") }

Resulting Error:

Go
Tutorials dojo strip