Go chapters

Chapter 7 of 17

Conditional Statements

Try this in our Go Compiler →

Making decisions

Real programs constantly choose between actions: log the user in or show an error, charge full price or apply a discount. The if statement is how Go expresses that choice. The condition is evaluated and if it is true the block runs; otherwise the else block (if present) runs instead.

score := 72
if score >= 90 {
    fmt.Println("A")
} else if score >= 60 {
    fmt.Println("Pass")
} else {
    fmt.Println("Fail")
}

else if and switch

When you have more than two branches, else if chains keep the code linear and easy to read. For matching a single value against many constants, some languages offer a switch or match statement that is cleaner than a long chain.

Truthy and falsy

Conditions follow Go's rules. Some languages convert values to booleans; others require a boolean expression. Check the language-specific details below rather than transferring truthiness rules.

Details for go

Conditions require bool; there is no integer or string truthiness. Go uses for and has no while keyword. Slices can share backing arrays; retain append's returned slice because it can reallocate.

Practice and verify

Change one meaningful value in the example and predict the result before running. Then test a boundary or empty value. Explain what changed and why, rather than only copying the output.

Try it yourself

Output
Run your project to see output here.
Ctrl/Cmd+Enter runs · Ctrl/Cmd+S downloads the project · Local auto-save is always on