Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 147 ยท Operators and Control Flow

if, else if and else

Learn Go's if statement - conditions without parentheses, else if chains, the init statement and its scope, early returns, and the comma-ok idiom for maps.

An if statement runs a block of code only when a condition is true. Go's version looks familiar if you have used C, Java or JavaScript, with three differences that shape everyday Go code: the condition has no parentheses, the braces are always required, and an if can start with a short init statement whose variables live only inside the if.

That last feature is what makes the famous Go pattern if err != nil so compact, and it is the main subject of this lesson. We will also look at how experienced Go programmers flatten their code with early returns, and at the comma-ok idiom you will use constantly with maps. The conditions themselves are built from the comparison and logical operators.

The basic if statement

Write if, a boolean expression, and a block. Add else for the alternative, and else if for further tests. Go checks the conditions from top to bottom and runs the first block whose condition is true.

Go if, else if and else

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Three rules are enforced by the compiler and by gofmt:

  • No parentheses around the condition. if (x > 3) { still compiles, but gofmt removes the parentheses.
  • Braces are mandatory, even for a single statement. There is no braceless if x > 3 return, which rules out the "goto fail" class of bugs.
  • The opening brace must be on the same line as if, and else must start on the same line as the closing brace: } else {. This follows from how Go inserts semicolons at line ends, covered in Go Syntax.

If you put else on its own line, the compiler complains:

Go else on its own line (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The error looks like this:

TEXT
./main.go:10:2: syntax error: unexpected keyword else, expected }

Go inserted a semicolon after the } at the end of line 9, so the if statement ended there and a lone else makes no sense. (The exact wording of syntax errors can change between Go versions; the position and the idea stay the same.)

Conditions must be booleans

The condition has to be of type bool. Go has no "truthy" and "falsy" values, so numbers, strings, pointers and slices cannot stand in for a condition. Compare explicitly instead.

Go A non-boolean condition (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The compiler says:

TEXT
./main.go:7:5: non-boolean condition in if statement

The fix is to say what you mean: if count != 0 or if count > 0. Being explicit also makes code easier to read, because the reader does not have to remember what counts as "empty" for each type.

The init statement

An if may begin with a simple statement, followed by a semicolon, and then the condition:

Go
if init; condition {
	...
}

The init statement is usually a short variable declaration. The variables it declares are visible in the condition, in the if block and in every else if or else block that follows, and nowhere else. When the if ends, they go out of scope.

Go Init statements and scope

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

strconv.Atoi returns two values, the number and an error. The init statement captures both, the condition checks the error, and the else branches can still use n. Once the whole if chain ends, both names are gone, so you cannot accidentally reuse a stale err later in the function.

Trying to use them after the if is a compile error, which makes a good demonstration of the scope rule:

Go Init variables are scoped to the if (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The error is ./main.go:12:14: undefined: n. If you need the value afterwards, declare the variable before the if and use = inside it:

Go
n, err := strconv.Atoi(text)
if err != nil {
	return err
}
fmt.Println(n) // fine: n is declared outside the if

Both forms are common. Use the init statement when the variables are only needed for the check and its branches, and a separate declaration when the rest of the function needs them. The Errors as Values lesson shows why if err != nil is the most common if in Go.

Early returns: keep the happy path left

Go code usually avoids deep nesting. Instead of wrapping the main logic in else blocks, handle the failure cases first and return early. The successful path then runs straight down the left edge of the function. The Go linters even flag an else that follows a return.

Go Nested style versus guard clauses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Both functions behave the same (the loop prints true for the comparison on each line), but the second reads like a checklist: nothing is nested more than one level, and the last line is the success case.

The comma-ok idiom

Several operations can report whether they succeeded as a second, boolean result, conventionally called ok. You have already met it if you have read a map: looking up a missing key returns the zero value, so you cannot tell "missing" from "present with the zero value". Capture the second result to find out. It fits an if init statement perfectly.

Go Map lookups with comma-ok

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The same v, ok shape appears for type assertions and for receiving from channels. See Maps, Type Assertions and Type Switches and Channels.

When an if/else if chain keeps testing the same value against several options, a switch statement is usually clearer. Use if for boolean conditions of different kinds, switch for choosing between many cases.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which of these compiles?

    The condition needs no parentheses and the braces are mandatory. Option 1 has no braces, option 3 uses a keyword Go does not have, and option 4 is Python syntax.
  2. 2. What happens with n := 4; if n { fmt.Println("yes") }?

    Go has no truthy values. A condition must have type bool, so write if n != 0.
  3. 3. In if v, err := f(); err != nil { ... } else { ... }, where can v be used?

    Variables declared in the init statement are scoped to the whole if/else chain and disappear when it ends.
  4. 4. Given m := map[string]int{"a": 0}, what does v, ok := m["a"] give?

    The key exists, so ok is true even though the stored value is the zero value. For a missing key, ok would be false.
  5. 5. Why do Go programmers prefer if err != nil { return err } followed by the main logic over wrapping the main logic in an else block?

    Early returns avoid deep nesting. The compiler accepts else after return, but linters flag it and the flat style is idiomatic.

Summary

  • An if has no parentheses around its condition, requires braces, and keeps } else { on one line.
  • The condition must be a bool; compare explicitly (n != 0, s != "", p != nil).
  • Chain tests with else if; the first true condition wins.
  • An init statement (if v, err := f(); err != nil) declares variables scoped to the whole if/else chain.
  • Prefer early returns and guard clauses to nested else blocks, so the happy path stays on the left.
  • The comma-ok idiom (v, ok := m[key]) distinguishes a missing key from a stored zero value.

Next: switch