If/Else
Branching with if and else in Go is straightforward. Go doesn't require parentheses around conditions, but braces are always required.
Key Points
- Parentheses around conditions are not used in Go
- Braces
{ }are always required, even for single statements - Variables declared in if statements are scoped to that block
- Go has no ternary operator - use if/else instead
Basic If Statement
package main
import "fmt"
func main() {
if 7%2 == 0 {
fmt.Println("7 is even")
} else {
fmt.Println("7 is odd")
}
}7 is oddIf Without Else
package main
import "fmt"
func main() {
if 8%4 == 0 {
fmt.Println("8 is divisible by 4")
}
}8 is divisible by 4If with Statement
You can declare variables scoped to the if statement:
package main
import "fmt"
func main() {
if num := 9; num < 0 {
fmt.Println(num, "is negative")
} else if num < 10 {
fmt.Println(num, "has 1 digit")
} else {
fmt.Println(num, "has multiple digits")
}
}9 has 1 digitIf/Else Reference
| Pattern | Example | Description |
|---|---|---|
if condition{ } | if x > 0 { } | Basic if statement |
if condition { } else { } | if x > 0 { } else { } | If-else statement |
if c1 { } else if c2 { } | if x < 0 { } else if x > 0 { } | If-else if chain |
if stmt; condition { } | if n := f(); n > 0 { } | If with initialization statement |