if and else work close to how they do everywhere else, with one Go-specific twist: no parentheses around the condition, and the braces are mandatory.
A bare if. Parentheses around the condition are optional in Go, but not idiomatic; gofmt strips them.
if age >= 18 {
fmt.Println("adult")
}Add an else branch for the case where the condition is false.
if score >= 60 {
fmt.Println("pass")
} else {
fmt.Println("fail")
}Chain else if to test multiple conditions top to bottom. The first match wins.
if score >= 90 {
grade = "A"
} else if score >= 80 {
grade = "B"
} else {
grade = "C"
}Go allows a short statement before the condition, separated by a semicolon. In a map lookup, ok reports whether the key existed; qty exists only inside the if/else block.
if qty, ok := stock["widget"]; ok && qty > 0 {
fmt.Printf("widget: %d in stock\n", qty)
}A full example combining both: checking stock levels for two products using the comma-ok map lookup inside an if init statement.
package main
import "fmt"
func main() {
stock := map[string]int{"widget": 12, "gadget": 0}
if qty, ok := stock["widget"]; ok && qty > 0 {
fmt.Printf("widget: %d in stock\n", qty)
} else {
fmt.Println("widget: out of stock")
}
if qty, ok := stock["gizmo"]; ok && qty > 0 {
fmt.Printf("gizmo: %d in stock\n", qty)
} else {
fmt.Println("gizmo: out of stock")
}
}"gizmo" isn't in the map, so ok is false and execution falls to the else branch.
$ go run if_else.go
widget: 12 in stock
gizmo: out of stock