Conditionals
if, else if, and else pick one branch of code to run based on a boolean test. Go drops the parentheses, requires the braces, and lets you declare variables in the if itself.
Detailed Explanation
An if statement asks a yes-or-no question and runs one block of code depending on the answer. That part is the same in every language you have used. What Go changes is the punctuation and the rules around it, and each change has a reason behind it.
No parentheses, mandatory braces. You write if age >= 18 {, not if (age >= 18) {. The braces are not optional even for a one-line body, and the opening brace must sit on the same line as the condition. This is not a style preference you can argue with; the compiler inserts semicolons at line ends, so a brace on the next line breaks the statement. gofmt will never reformat an if into a different shape, which means every Go codebase you read looks the same here.
Conditions must be of type bool. There is no truthiness in Go. An empty string is not false. A zero is not false. A nil pointer is not false. if len(name) { ... } does not compile — it is a type error, not a warning. You write if name == "" { ... } or if len(items) > 0 { ... }. This removes a whole family of bugs where a value of 0 and a value of "missing" were accidentally the same thing.
The init statement is the idiom that matters. An if can run one statement before evaluating its condition, separated by a semicolon: if v, err := f(); err != nil { ... }. The variables declared there live only inside the if and its else branches, and vanish at the closing brace. That scoping is the whole point. When you parse ten config values in one function, you do not want ten err variables cluttering the function body, and you do not want to accidentally check a stale err from three calls ago. The init statement makes the error's lifetime exactly as long as the check that uses it.
The paired convention is the early return. Handle the failure inside the if, return, and let the successful path continue at the outer indentation level. Go code tends to read as a flat column of checks followed by the real work, rather than a pyramid of nested success branches.
There is no ternary operator. Go has no cond ? a : b. The language designers argued that ternaries start out readable and end up nested and unreadable, and that a three-line if costs almost nothing. So you write a small if, or a named helper function if you need the value inline. That verbosity is the deliberate trade: more lines, but every branch is visible and greppable.
What it costs. Nothing at runtime — branches compile to the same comparisons and jumps any language would emit. The cost is in keystrokes and vertical space. A chain of if err != nil blocks takes up real screen area, and that is the most common complaint about reading Go. The upside is that every place an operation can fail is marked in the source.
Code Examples
package main
import (
"fmt"
"strconv"
)
func main() {
// No parentheses around the condition. Braces are always required,
// even for a single-line body.
age := 20
if age >= 18 {
fmt.Println("adult")
} else if age >= 13 {
fmt.Println("teenager")
} else {
fmt.Println("child")
}
// Init statement: run one statement, then test its result.
// port and err exist only inside this if/else chain.
if port, err := strconv.Atoi("8080"); err != nil {
fmt.Println("bad port:", err)
} else {
fmt.Println(port + 1) // 8081
}
// Conditions must be bool. `if len(name) { ... }` is a compile error.
name := ""
if name == "" {
fmt.Println("name is empty")
}
}The canonical shape: call, check, handle, return early.
// The canonical shape: call, check, handle, return early.
// The happy path stays at the left margin instead of nesting.
func loadPort(raw string) (int, error) {
port, err := strconv.Atoi(raw)
if err != nil {
return 0, fmt.Errorf("parse port %q: %w", raw, err)
}
if port < 1 || port > 65535 {
return 0, fmt.Errorf("port %d out of range", port)
}
return port, nil
}
// When the value is not needed, fold the call into the if so that
// err cannot leak into the rest of the function.
func writeAll(w io.Writer, b []byte) error {
if _, err := w.Write(b); err != nil {
return err
}
return nil
}Go has no ternary operator. Write the if, or wrap it in a helper
// Go has no ternary operator. Write the if, or wrap it in a helper
// when you need the result inline.
func label(passed bool) string {
if passed {
return "pass"
}
return "fail"
}Common Gotchas
There is no truthiness
the condition must have type `bool`. `if count { ... }`, `if ptr { ... }`, and `if s { ... }` are all compile errors. Compare explicitly: `count != 0`, `ptr != nil`, `s != ""`.
Init-statement variables die at the closing brace
`if v, err := f(); err == nil { ... }` leaves `v` unreachable after the block. If you need the value later, declare it before the `if` instead.
`else` after a `return` is dead weight
if the `if` branch returns, drop the `else` and unindent its body. This is the single most common review comment on new Go code.