Conditions and switch

Introduction

Programs make decisions all the time: is the password right, is the number negative, is it the weekend? In Go, decisions are written with if and switch. Both look at a condition or a value and choose which block of code runs. Go keeps the rules simple, so there are no brackets around conditions and no surprises with switch cases that run into each other. This lesson shows how to write clear decisions and how to combine several conditions.

How it works

An if statement runs a block when its condition is true. The condition must be a bool: Go does not accept a number as a condition. The braces are always required, even for one line, and the opening brace must be on the same line as the if.

if score >= 90 {
	fmt.Println("A")
} else if score >= 80 {
	fmt.Println("B")
} else {
	fmt.Println("C or lower")
}

The comparison operators are ==, !=, <, <=, > and >=. They give true or false. To combine conditions, use && (and), || (or) and ! (not). a && b is true only when both are true; Go does not even look at b if a is false.

An if may start with a short statement, then a semicolon and the condition. A variable made there exists only inside the if and its else parts, which keeps the rest of the code clean:

if r := n % 2; r == 0 {
	fmt.Println("even")
}

A switch compares one value with several cases and runs the first case that matches. A case can list several values separated by commas, and default runs when nothing matches. Unlike in C or Java, Go does not run on into the next case, so you do not write break.

switch day {
case 1, 7:
	fmt.Println("weekend")
case 2, 3, 4, 5, 6:
	fmt.Println("weekday")
default:
	fmt.Println("not a day")
}

A switch with no value after the word switch checks each case as a condition. It reads like a tidy list of else if parts, and it is often the best way to write a chain of ranges.

Example

package main

import "fmt"

func main() {
	var score, day int
	fmt.Scan(&score, &day)

	if score >= 90 {
		fmt.Println("grade A")
	} else if score >= 80 {
		fmt.Println("grade B")
	} else {
		fmt.Println("grade C or lower")
	}

	if r := score % 2; r == 0 {
		fmt.Println("even score")
	} else {
		fmt.Println("odd score, remainder", r)
	}

	switch day {
	case 1, 7:
		fmt.Println("weekend")
	case 2, 3, 4, 5, 6:
		fmt.Println("weekday")
	default:
		fmt.Println("not a day")
	}

	switch {
	case score < 50 && day == 7:
		fmt.Println("study on Sunday")
	case score < 50:
		fmt.Println("needs work")
	default:
		fmt.Println("well done")
	}
	fmt.Println(score >= 50 && day != 7, score < 50 || day == 7, !(score >= 50))
}

Input used: 85 7

Line by line

  1. fmt.Scan(&score, &day) reads two numbers.
  2. The if, else if, else chain chooses the first condition that is true and prints a grade.
  3. if r := score % 2; r == 0 makes r only for this if.
  4. The first switch compares day with the values in each case; 1 and 7 share one case.
  5. The second switch has no value, so each case is a condition, and && joins two tests in the first one.
  6. The last line prints three combined conditions: &&, || and !.

Expected result

With this input:

85 7

it prints:

grade B
odd score, remainder 1
weekend
well done
false true false

In the real world

Every program that checks input uses decisions: a login form compares a password, a shop applies a discount above a limit, a game checks whether the player is still alive. A switch on a command word is the usual way to build a menu or a small command-line tool, and you will use it in the last lesson of this course.

Common mistakes

  • Putting the opening brace on a new line. In Go it must stay on the line of the if.
  • Writing if x = 5 instead of ==. A single = assigns, and Go reports an error.
  • Using a number as a condition. Write n != 0, not n.
  • Expecting a switch to fall through like in C. Each case stops by itself.
  • Forgetting default, so an unexpected value does nothing at all.

Best practices

  • Put the most likely or most important case first, and handle errors early.
  • Use a value-less switch instead of a long else-if chain.
  • Name complex conditions with a variable, such as isWeekend := day == 1 || day == 7.

Summary

if, else if and else choose a block by a bool condition, and conditions are joined with &&, || and !. An if can start with a short statement whose variable lives only in the if. A switch compares a value with cases that may list several values; it never falls through, and a switch without a value checks conditions.

Quick check

1. Which of these is a valid if condition in Go?
2. What does a switch case do after its code has run?
3. What does a switch with no value after the word switch do?
4. What is true && false || true?
5. Where can the variable r in if r := n % 2; r == 0 be used?

Key takeaways

  • An if needs a true or false condition with no brackets around it, and the braces are always required.
  • && needs both sides true, || needs one, and ! reverses; they stop early when the answer is clear.
  • A Go switch does not fall through: only the matching case runs, and a case can list many values.

Practice problems for this lesson

Was this lesson clear?

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.