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.
Syntax
The structure of an if else
statement in Go is:
if condition { // Code to execute if the condition is true } else { // Code to execute if the condition is false }
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.
package main import ("fmt") func main() { time := 20 if time < 18 { fmt.Println("Good afternoon.") } else { fmt.Println("Good evening.") } }
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
package main import ("fmt") func main() { hondaSpeed := 75 suzukiSpeed := 85 if hondaSpeed > suzukiSpeed { fmt.Println("Honda is faster than Suzuki.") } else { fmt.Println("Suzuki is faster than Honda.") } }
Explanation of Example 2
In this example:
- The variables
hondaSpeed
andsuzukiSpeed
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 than85
(Suzuki’s speed), the code in theelse
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 theif
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:
./prog.go:9:3: syntax error: unexpected else, expecting }