if / else Statements
Basic if / else
An if statement runs a block only when its condition evaluates to true, and an optional else block runs otherwise. Unlike C or Java, the condition is never wrapped in parentheses, and the braces are always required, even for a single statement.
Note: Go never requires (or wants) parentheses around the condition.
Example: Basic if / else
package main
import "fmt"
func main() {
age := 20
if age >= 18 {
fmt.Println("adult")
} else {
fmt.Println("minor")
}
}
Login to try C/C++/Java/PHP code in the editor
else if Chains
Multiple conditions can be chained with 'else if', evaluated top to bottom until one is true, falling through to a final else if none match -- useful for handling several mutually exclusive cases.
Example: else if Chains
package main
import "fmt"
func main() {
score := 72
if score >= 90 {
fmt.Println("Grade A")
} else if score >= 75 {
fmt.Println("Grade B")
} else if score >= 60 {
fmt.Println("Grade C")
} else {
fmt.Println("Grade F")
}
}
Login to try C/C++/Java/PHP code in the editor
if with an Init Statement
Go lets you run a short statement before the condition, separated by a semicolon, most often used to assign a value and immediately test it -- a pattern very common with functions that return a value and an error.
Note: Variables declared in an if's init statement are only visible within that if/else chain.
Example: if with an Init Statement
package main
import "fmt"
func half(n int) (int, bool) {
if n%2 != 0 {
return 0, false
}
return n / 2, true
}
func main() {
if result, ok := half(10); ok {
fmt.Println("half is:", result)
} else {
fmt.Println("not evenly divisible")
}
}
Login to try C/C++/Java/PHP code in the editor
Boolean Expressions
Conditions combine comparisons with && (and), || (or), and ! (not), just like most C-family languages, and Go short-circuits these operators, stopping evaluation as soon as the result is determined.
Example: Boolean Expressions
package main
import "fmt"
func main() {
age := 25
hasID := true
if age >= 18 && hasID {
fmt.Println("entry allowed")
}
}
Login to try C/C++/Java/PHP code in the editor
- Wrapping the condition in parentheses like 'if (x > 5)' -- Go allows it but idiomatic style always omits them.
- Forgetting that the opening brace must be on the same line as if/else -- Go's automatic semicolon insertion breaks otherwise.
- Not realizing a variable declared in the if's init statement (if x := f(); x > 0) is scoped only to the if/else chain, not outside it.
- if/else branches based on a boolean condition, with no parentheses required around the condition.
- An optional init statement can run before the condition, scoping a variable to the whole if/else chain.
- else if chains multiple conditions together.
- Braces are mandatory in Go, unlike some C-family languages that allow single-statement bodies without them.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: