If Statements in Go
Table of Contents
if statements in Go do not use parentheses around the condition.
All the content from our Boot.dev courses are available for free here on the blog. This one is the "Conditionals" chapter of Learn Go. If you want to try the far more immersive version of the course, do check it out!
If Statement Syntax
if height > 4 {
fmt.Println("You are tall enough!")
}
else if and else are supported as you might expect:
if height > 6 {
fmt.Println("You are super tall!")
} else if height > 4 {
fmt.Println("You are tall enough!")
} else {
fmt.Println("You are not tall enough!")
}
Unlike other languages, you must put the opening brace on the same line as the condition and not on a new line.
If you find yourself chaining a lot of else if blocks, you probably want a switch statement instead.
Comparison Operators
Here are some of the comparison operators in Go:
==equal to!=not equal to<less than>greater than<=less than or equal to>=greater than or equal to
The Initial Statement of an If Block
An if conditional can have an "initial" statement. The variable(s) created in the initial statement are only defined within the scope of the if, else if, and else blocks.
if INITIAL_STATEMENT; CONDITION {
}
Why Would I Use This?
It has two valuable purposes:
- It's a bit shorter
- It limits the scope of the initialized variable(s) to the
ifstatement
For example, instead of writing:
length := getLength(email)
if length < 10 {
fmt.Printf("Email must be at least 10 characters, is %d\n", length)
}
We can do:
if length := getLength(email); length < 10 {
fmt.Printf("Email must be at least 10 characters, is %d\n", length)
}
In the example above, length isn't available in the parent scope, which is nice because we don't need it there - we won't accidentally use it elsewhere in the function. It would still be available in any else if or else blocks attached to that if.
The Modulo Operator
Go supports the standard modulo operator. It's useful in if conditions for checking divisibility:
7 % 3 // 1
Logical Operators
The AND logical operator:
true && false // false
true && true // true
As well as the OR operator:
true || false // true
false || false // false
Frequently Asked Questions
Do Go if statements need parentheses?
No. If statements in Go do not use parentheses around the condition.
Does Go support else if and else?
Yes. Else if and else are supported, and the opening brace must be on the same line as the condition.
Can a Go if statement have an initial statement?
Yes. Variables created in the initial statement are only defined within the scope of the if, else if, and else blocks.
What do the && and || logical operators do in Go?
The AND operator, &&, is true when both values are true. The OR operator, ||, is true when either value is true.
