LESSON · 1 OF 17

The if statement

The if statement

The if statement runs a block of code only when a condition is true. You can chain alternatives with else if and a final else.

go
if count > 10 {
    fmt.Println("high")
} else if count > 0 {
    fmt.Println("some")
} else {
    fmt.Println("none")
}

Go checks each condition top to bottom and runs the first block whose condition is true. The else block runs when none of them matched.

Two rules make Go's if different from many other languages. The condition needs no parentheses - you write if count > 10, not if (count > 10). And the braces are always required, even for a single line. There is exactly one correct layout, so every Go if looks the same.

Spin up a fresh environment and practice live.
go · fresh machine · ready in under a minute