Skip to content

Beginner · Control flow and functions · topic 6 of 46 · 30 min

Decisions with if and switch

Explanation

if runs a block only when a condition is true; Go needs no brackets around the condition but always needs braces. An if can start with a short statement, like reading a value, before the condition. switch picks one case out of many and, unlike C or Java, does not fall through to the next case.

Why decisions?

Programs must react: if the payment failed, show an error; if the cart is above ₹199, delivery is free. A condition is an expression that is either true or false, such as total > 199 or name == "Asha".

if, else if, else

go
total := 250
if total >= 199 {
	fmt.Println("Free delivery")
} else if total >= 99 {
	fmt.Println("Delivery: Rs 20")
} else {
	fmt.Println("Delivery: Rs 40")
}
Prints Free delivery. Only the first true branch runs.
  • No round brackets are needed around the condition: if total >= 199 {.
  • Braces are always required, even for one line.
  • The condition must be a bool. if count { } is a compile error when count is an int; write if count > 0 { }.
  • else must be on the same line as the closing brace: } else {.

Comparison and logic operators

OperatorMeaningExample
== and !=equal, not equalcity == "Pune"
< <= > >=less / greaterage >= 18
&&and: both must be trueage >= 18 && hasID
||or: at least one trueisAdmin || isOwner
!not!paid

&& and || are short-circuit: if the left side already decides the answer, the right side is not evaluated. So if user != nil && user.Active is safe: when user is nil, user.Active is never read.

if with a short statement

An if can begin with a short statement, a semicolon, then the condition. Variables declared there exist only inside the if and its else branches. This keeps them out of the way and is the normal Go style for checking errors.

go
if n, err := strconv.Atoi("42"); err == nil {
	fmt.Println("number:", n)
} else {
	fmt.Println("bad input:", err)
}
// n and err do not exist here
The scope of n and err is only the if/else.

switch: many choices, cleanly

go
day := "Sun"
switch day {
case "Sat", "Sun":
	fmt.Println("Weekend: shop opens at 10")
case "Fri":
	fmt.Println("Friday: open till late")
default:
	fmt.Println("Weekday: shop opens at 9")
}
A case can list several values. default runs when no case matches.

Go's switch stops after the first matching case. You do not write break. If you really want to continue into the next case, write fallthrough, which runs the next case's body without checking its condition. It is rarely needed.

switch with no value: a cleaner if-else chain

go
marks := 72
switch {
case marks >= 90:
	fmt.Println("A")
case marks >= 75:
	fmt.Println("B")
case marks >= 40:
	fmt.Println("C")
default:
	fmt.Println("Fail")
}
switch with nothing after it is the same as switch true. Cases are checked top to bottom. Prints C.
Careful: Common mistake from C/Java: writing break in every case. It is harmless but unnecessary. The opposite mistake: expecting a case to fall through. In Go, case 1: (empty) does NOT run case 2's code. Use case 1, 2: instead.
Careful: Order matters in a no-value switch. If you write case marks >= 40 before case marks >= 90, a student with 95 gets C. Put the strictest condition first.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Decisions with if and switch · 1/7

if · else · switch

Programs make decisions all the time. In Go we use if and switch.

Prefer a video by a teacher? Find free videos on “golang if else switch statement tutorial” on YouTube ↗

In real life: IRCTC-style ticket fare by class

A railway booking service works out the base fare from the class of travel and adds a Tatkal charge when the booking is Tatkal. A switch on the class code keeps all fares in one easy-to-read place, and an if adds the extra charge.

go
package main

import "fmt"

func main() {
	class := "3A"
	tatkal := true
	fare := 0

	switch class {
	case "SL":
		fare = 450
	case "3A":
		fare = 1200
	case "2A", "1A":
		fare = 1800
	default:
		fmt.Println("unknown class")
		return
	}
	if tatkal {
		fare += 400
	}
	fmt.Println("Fare:", fare) // Fare: 1600
}
The fares are made-up numbers; the structure is what matters.

Practice (0/4 done)

Task 1 · Question

What does this print? x := 5 switch x { case 5: fmt.Println("five") case 6: fmt.Println("six") }

Task 2 · Question

Which line is the bug? 1: count := 3 2: if count { 3: fmt.Println("has items") 4: }

Task 3 · Question

What does this print? marks := 95 switch { case marks >= 40: fmt.Println("C") case marks >= 90: fmt.Println("A") }

Task 4 · Practice

Write a program that sets a variable units (electricity units used) and prints the bill slab: up to 100 units "Slab 1", 101 to 300 "Slab 2", above 300 "Slab 3". Then use a switch on a month string to print "Summer" for "Apr", "May", "Jun" and "Other" otherwise.

Quick quiz

Question 1

1.In if v, err := f(); err != nil { ... }, where can v be used?

Question 2

2.What does the keyword fallthrough do?

Question 3

3.user is nil. Is if user != nil && user.Active safe?

Question 4

4.How do you make one switch case match both 1 and 2?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

In if v, err := f(); err != nil { ... }, where can v be used?

Answer: Only inside the if and its else branches

Variables declared in the if statement are scoped to the if/else blocks.

What does the keyword fallthrough do?

Answer: Runs the next case body without checking its condition

fallthrough transfers control to the next case body unconditionally.

user is nil. Is if user != nil && user.Active safe?

Answer: Yes, && stops after the false left side

&& short-circuits: the right side is never evaluated when the left is false.

How do you make one switch case match both 1 and 2?

Answer: case 1, 2:

List several values separated by commas in one case.

A switch case has code but no break. What happens?Related

Answer: Compile error: control cannot fall through

C# does not allow fall-through from a non-empty case (error CS0163).

From Decisions: if, else, switch and switch expressions

Which type can NOT be used in a switch?Related

Answer: std::string

switch needs an integral or enum value. Use if / else if for strings.

From Operators and decisions: if, else and switch

Which types can a standard C switch use?Related

Answer: Integer types like int, char and enums

Case labels must be integer constants.

From Decisions: if, else and switch

How many branches of if / else if / else can run?Related

Answer: At most one

Only the first true branch runs.

From Decisions: if, else and the ternary

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 4 more topics in “Control flow and functions” before its exam: Loops: for is the only loop, Functions and multiple return values, Variadic functions, function values and closures, defer: clean up at the end.
  2. Module 2 exam: Control flow and functions · 13 questions · 20 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Collections and structs. 46 topics left in the course before the final exam.

← Previous: Constants, iota and type conversions