Learn Go← Dashboard

if/else, switch, the lone for loop, break, continue.

if / else

Go's if is the regular if — with two small extras: no parentheses around the condition, and an optional init statement before the condition.

Basics

if x > 0 {
    fmt.Println("positive")
} else if x < 0 {
    fmt.Println("negative")
} else {
    fmt.Println("zero")
}

Curly braces are required — even for a one-liner. There is no "trailing if" like Ruby's puts "hi" if cond.

The init statement

You can declare a variable directly in the if. It's scoped to the if/else chain and disappears afterwards:

go playground
Loading...

This is the canonical idiom for handling functions that return (value, error) — parse, check, branch, all in one line.

Conditions must be bool

n := 1
if n {           // compile error — n is int, not bool
    ...
}

There's no truthy/falsy. Write the comparison: if n != 0 { ... }.

What's the scope of `n` in `if n, err := foo(); err == nil { ... } else { ... }`?