if and else in Go
Go’s if is simple and can include a short initialization statement.
Basic
A standard conditional with braces. Conditions must be boolean—no implicit int-to-bool.
if x > 0 {
// ...
} else {
// ...
}
Else-if
Chain additional conditions using else if. Prefer small, readable branches over deep nesting.
if n < 0 {
// negative
} else if n == 0 {
// zero
} else {
// positive
}
Short statement
Declare and initialize a temporary that’s scoped to the if/else blocks.
if v := compute(); v > 10 {
// v is in scope here
} else {
// and here
}
// v is out of scope here
With errors
The idiomatic pattern: do work, check err, and return early. Keeps happy path left-aligned.
if v, err := parse("42"); err != nil {
// handle
} else {
_ = v // use v
}
Truthiness
- Only booleans are allowed (no implicit int-to-bool)
- Zero values:
falsefor bool; check explicitly for other types
// bad: if s { ... } // s is string
// good:
if s != "" { /* ... */ }
Tips
- Return early inside
if err != nilto avoid nesting - Keep conditions readable; extract into a named variable when complex
- Avoid deep
elsechains; consider guard clauses
if err != nil { return err } // guard clause
// proceed with success path
Summary
- Use short init statements for scoped temps
- Prefer early returns for clarity