Beginner · Control flow and functions · topic 6 of 46 · 30 min
Decisions with if and switch
Explanation
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
total := 250
if total >= 199 {
fmt.Println("Free delivery")
} else if total >= 99 {
fmt.Println("Delivery: Rs 20")
} else {
fmt.Println("Delivery: Rs 40")
}- 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
| Operator | Meaning | Example |
|---|---|---|
| == and != | equal, not equal | city == "Pune" |
| < <= > >= | less / greater | age >= 18 |
| && | and: both must be true | age >= 18 && hasID |
| || | or: at least one true | isAdmin || 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.
if n, err := strconv.Atoi("42"); err == nil {
fmt.Println("number:", n)
} else {
fmt.Println("bad input:", err)
}
// n and err do not exist hereswitch: many choices, cleanly
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")
}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
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")
}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
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.
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
}Practice (0/4 done)
What does this print? x := 5 switch x { case 5: fmt.Println("five") case 6: fmt.Println("six") }
Which line is the bug? 1: count := 3 2: if count { 3: fmt.Println("has items") 4: }
What does this print? marks := 95 switch { case marks >= 40: fmt.Println("C") case marks >= 90: fmt.Println("A") }
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
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Loops: for is the only loopControl flow and functions · same module
- Functions and multiple return valuesControl flow and functions · same module
- Variadic functions, function values and closuresControl flow and functions · same module
- Decisions: if, else, switch and switch expressionsC# and .NET · Decisions, loops and methods
- Operators and decisions: if, else and switchC++ Programming (modern C++ and DSA) · Decisions, loops and functions
- Decisions: if, else and switchC Programming (from zero to systems) · Operators and control flow
Questions people ask about this
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).
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.
Which types can a standard C switch use?Related
Answer: Integer types like int, char and enums
Case labels must be integer constants.
How many branches of if / else if / else can run?Related
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
- 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.
- Module 2 exam: Control flow and functions · 13 questions · 20 min, without help. 5 topics of this module still to finish first.
- Then the next module, Collections and structs. 46 topics left in the course before the final exam.