Conditionals in Go

Learn to control the flow of a Go program with if, else if and else, the if-with-statement form, and switch, with clear runnable examples.

Prerequisites

Learning objectives

  • Write if, else if and else branches with the right operators
  • Use the if-with-statement form to scope a variable to its check
  • Choose between an expression switch and a tagless switch

Conditionals let a program choose what to do based on a boolean condition. Go gives you two tools: the if statement and the switch statement. Conditions are never wrapped in parentheses, and the braces are always required.

if, else if and else

An if runs its block when the condition is true. You can chain alternatives with else if and provide a fallback with else.

age := 20
if age >= 18 {
	fmt.Println("You can vote.")
} else if age >= 16 {
	fmt.Println("Almost there.")
} else {
	fmt.Println("Too young to vote.")
}

Only one branch runs: Go evaluates the conditions from top to bottom and stops at the first one that is true.

The if with a short statement

An if may start with a short statement that runs before the condition. Any variable it declares is scoped to the if and its else branches, which keeps short-lived values out of the surrounding function. This is the idiomatic way to handle an error right where it is produced:

if n, err := strconv.Atoi("42"); err == nil {
	fmt.Println(n + 1)
} else {
	fmt.Println("not a number:", err)
}

Here n and err do not exist after the if block, so they cannot leak into the rest of the function or be reused by mistake.

switch

A switch compares a value against several cases. Unlike C, Go does not fall through to the next case, so you never write break. A single case can also match a list of values.

switch day {
case "Sat", "Sun":
	fmt.Println("weekend")
default:
	fmt.Println("weekday")
}

A switch with no expression (a tagless switch) is a clean replacement for a long if/else if chain: the first case whose condition is true wins.

switch {
case score >= 90:
	fmt.Println("A")
case score >= 80:
	fmt.Println("B")
default:
	fmt.Println("C or below")
}

Comparison and boolean operators

Conditions are built from comparison operators — ==, !=, <, <=, >, >= — combined with the boolean operators && (and), || (or) and ! (not). Both && and || short-circuit: they stop as soon as the result is known.

if n > 0 && n%2 == 0 {
	fmt.Println("positive and even")
}

A complete example

The program below parses a string, classifies the number, and demonstrates both switch forms. It compiles and runs as-is.

package main

import (
	"fmt"
	"strconv"
)

func main() {
	raw := "42"

	// if with a short statement: n and err are scoped to the if.
	n, err := strconv.Atoi(raw)
	if err != nil {
		fmt.Printf("%q is not a valid number\n", raw)
		return
	}

	// if / else if / else with comparison and boolean operators.
	if n > 0 && n%2 == 0 {
		fmt.Printf("%d is positive and even\n", n)
	} else if n > 0 {
		fmt.Printf("%d is positive and odd\n", n)
	} else if n == 0 {
		fmt.Println("the value is zero")
	} else {
		fmt.Printf("%d is negative\n", n)
	}

	// Tagless switch: the first true case wins, no break needed.
	switch {
	case n < 10:
		fmt.Println("one digit")
	case n < 100:
		fmt.Println("two digits")
	default:
		fmt.Println("many digits")
	}

	// Expression switch with a case list.
	switch n % 3 {
	case 0:
		fmt.Println("divisible by three")
	case 1, 2:
		fmt.Println("not divisible by three")
	}
}

Running it prints:

42 is positive and even
two digits
divisible by three

Common mistakes

  • Adding parentheses around the condition. Write if n > 0 {, not if (n > 0) {. gofmt will not remove them, but they are not idiomatic.
  • Expecting fallthrough. In Go a case does not continue into the next one. List several values in one case instead of stacking empty cases.
  • Comparing incompatible types. == requires both sides to have the same type; convert one side first, for example float64(i) == f.

Practice

Given score := 84, print a single letter grade: A for 90 or more, B for 80 to 89, C for 70 to 79, and F otherwise.

Show the solution
package main

import "fmt"

func main() {
	score := 84

	switch {
	case score >= 90:
		fmt.Println("A")
	case score >= 80:
		fmt.Println("B")
	case score >= 70:
		fmt.Println("C")
	default:
		fmt.Println("F")
	}
}

The cases are ordered from the highest threshold down, so the first one that matches (score >= 80) wins and the program prints B.

Summary

  • if, else if and else run exactly one branch, without parentheses.
  • The if-with-statement form scopes a value to its own check.
  • switch never falls through by default; a tagless switch replaces long if chains.

Next, learn how to repeat work with loops in Go, then group your logic into functions.

Your progress is stored only in this browser. No account is required.

Search

Search runs entirely in your browser.