SyntaxPilot
Courses/Go Programming/Lesson 7

Go Programming · Lesson 7 of 89 · 12 min

Control flow: if and switch

ifelse ifelseif with init statementno ternary operatorswitch with valuescase listsswitch without condition (switch true)fallthroughbreak in switchswitch init statement

These are the notes for Go episode 7. Until now, every program ran every line, top to bottom. Today your programs learn to choose. You will learn if, else if and else (and why the order of checks matters), Go's strict rules (braces always, a real bool condition, } else { on one line), why Go has no ternary operator, the if init statement and its scope, switch with values and case lists, default, why Go needs no break in a switch, the fallthrough keyword, break inside a switch, the condition-less switch (switch true) and the switch init statement. Every example runs as-is in the SyntaxPilot compiler (language: Go); outputs and errors are from real runs (Go 1.24).

First, three words used all the way through:

  • Control flow is the order in which a program's lines run. Normally that is top to bottom; if, switch and (next episode) loops change it.
  • A condition is an expression that gives a bool: true or false. Example: age < 12.
  • A block is a group of statements inside curly braces { }. A block runs as one unit: all of it, or none of it.

The problem: one cinema, three prices

A cinema charges Rs 100 for children under 12, Rs 120 for people aged 60 and above, and Rs 200 for everyone else. The person at the counter looks at your age and picks one price. With what we know so far, a program can't do that:

package main

import "fmt"

func main() {
    age := 8
    fmt.Println("age:", age)
    fmt.Println("child ticket: 100")
    fmt.Println("senior ticket: 120")
    fmt.Println("adult ticket: 200")
}
age: 8
child ticket: 100
senior ticket: 120
adult ticket: 200

Every line always runs, so the program prints all three prices. We need a way to say: run this line only when something is true.

if: run a block only when a condition is true

package main

import "fmt"

func main() {
    age := 8
    price := 200
    if age < 12 {
        price = 100
    }
    fmt.Println("ticket:", price)
}
ticket: 100
  • if, then a condition, then a block in braces. The block runs only when the condition is true.
  • Here price starts at 200, the usual price. If age < 12, the block changes it to 100. If age were 30, the block would be skipped and the price would stay 200.

The shape:

if condition {
    // runs only when condition is true
}

Go's three if rules

  1. The condition must be a bool. Some languages treat a non-zero number as "true". Go doesn't.
  2. Braces are always required, even for a single line.
  3. No round brackets are needed around the condition. You may write if (age < 12) {; it works, and gofmt (Go's formatter, episode 1) rewrites it to if age < 12 {.

Breaking rule 2:

package main

import "fmt"

func main() {
    age := 8
    if age < 12 fmt.Println("ticket: 100")
}
# command-line-arguments
./main.go:7:17: syntax error: unexpected name fmt, expected {
./main.go:8:1: syntax error: unexpected }, expected expression

A syntax error means the code isn't written in a shape Go's grammar accepts. Go wants { right after the condition.

Breaking rule 1:

package main

import "fmt"

func main() {
    age := 8
    if age {
        fmt.Println("has an age")
    }
}
# command-line-arguments
./main.go:7:8: non-boolean condition in if statement

age is an int, not a bool. Write exactly what you mean: if age > 0 {.

else if and else: one question, one answer

The obvious way to handle three prices is three separate ifs. Try it with a 70-year-old customer:

package main

import "fmt"

func main() {
    age := 70
    if age < 12 {
        fmt.Println("child: 100")
    }
    if age >= 12 {
        fmt.Println("adult: 200")
    }
    if age >= 60 {
        fmt.Println("senior: 120")
    }
}
adult: 200
senior: 120

Two tickets! A 70-year-old is "12 or more" and "60 or more", so both blocks ran. Separate ifs are separate questions; we want one question with several possible answers, where only one wins.

The fix is a chain:

package main

import "fmt"

func main() {
    age := 70
    if age < 12 {
        fmt.Println("child: 100")
    } else if age >= 60 {
        fmt.Println("senior: 120")
    } else {
        fmt.Println("adult: 200")
    }
}
senior: 120
  • else if adds another condition to the same chain; else means otherwise: "none of the above".
  • Go checks the conditions from the top. The first true one runs its block, and the rest of the chain is skipped. Exactly one block of a chain runs (or none, if there is no else and nothing matched).
  • Order matters. If you check age >= 12 before age >= 60, a 70-year-old matches the first one and pays 200; the senior check never gets a chance:
package main

import "fmt"

func main() {
    age := 70
    if age < 12 {
        fmt.Println("child: 100")
    } else if age >= 12 {
        fmt.Println("adult: 200")
    } else if age >= 60 {
        fmt.Println("senior: 120")
    }
}
adult: 200

Rule of thumb: put the narrowest (most specific) checks first.

} else { must be on one line

package main

import "fmt"

func main() {
    age := 30
    if age < 12 {
        fmt.Println("child: 100")
    }
    else {
        fmt.Println("adult: 200")
    }
}
# command-line-arguments
./main.go:10:5: syntax error: unexpected keyword else, expected }

Remember semicolon insertion from episode 1: Go's lexer (the part of the compiler that splits code into words) adds an invisible ; at the end of a line that ends with }. That ends the if statement, so the else on the next line has nothing to attach to. Always write } else { and } else if ... { on one line. gofmt formats it this way too.

No ternary operator

C, Java and JavaScript have a one-line "choose a value" operator: condition ? a : b. It's called the ternary operator (ternary = "three parts"). Go doesn't have it:

package main

import "fmt"

func main() {
    age := 8
    price := age < 12 ? 100 : 200
    fmt.Println(price)
}
# command-line-arguments
./main.go:7:23: invalid character U+003F '?'
./main.go:7:25: syntax error: unexpected literal 100 at end of statement

U+003F is the Unicode code number for ?. Go's FAQ explains the decision: the designers had seen the operator "used too often to create impenetrably complex expressions", and "a language needs only one conditional control flow construct". The Go way is a variable plus an if:

package main

import "fmt"

func main() {
    age := 8
    price := 200
    if age < 12 {
        price = 100
    }
    fmt.Println(price)
}
100

Or, when both values need computing, if/else:

package main

import "fmt"

func main() {
    age := 30
    var price int
    if age < 12 {
        price = 100
    } else {
        price = 200
    }
    fmt.Println(price)
}
200

if with an init statement

A food app gives free delivery on bills over Rs 500. We need the bill only to make this one decision. Go lets you create it inside the if:

if bill := price * qty; bill > 500 {
   └── init statement ──┘  └ condition ┘

The part before the semicolon is the init statement (short for initialisation). It runs first, then the condition is checked. What about using bill afterwards?

package main

import "fmt"

func main() {
    price, qty := 120, 5
    if bill := price * qty; bill > 500 {
        fmt.Println("free delivery on", bill)
    }
    fmt.Println(bill)
}
# command-line-arguments
./main.go:10:17: undefined: bill

A variable made in an init statement exists only inside that if, its else ifs and its else. That's block scope (episode 3): a variable lives only inside the block where it's created. It's a feature: the helper variable can't leak out and be misused later. Use it inside the chain:

package main

import "fmt"

func main() {
    price, qty := 120, 5
    if bill := price * qty; bill > 500 {
        fmt.Println("free delivery on", bill)
    } else {
        fmt.Println("add", 501-bill, "more")
    }
}
free delivery on 600

The else block can use bill too: 501-bill would tell a customer with a smaller bill how much more to add. You'll see this pattern constantly with errors later: if err := doSomething(); err != nil { ... }.

switch: one value, many cases

A railway helpline says: press 1 for a new booking, 2 to cancel, 3 or 4 for refund status, anything else to talk to an agent. With if, that's key == 1, else if key == 2, else if key == 3 || key == 4... The same variable, compared again and again. A switch is the phone menu in code:

On the phone In Go Meaning
The key you press switch key { the value to check
"Press 1 for booking" case 1: runs when key == 1
"3 or 4 for refunds" case 3, 4: a case list: any of these values
Anything else: an agent default: runs when no case matches
package main

import "fmt"

func main() {
    key := 2
    switch key {
    case 1:
        fmt.Println("new booking")
    case 2:
        fmt.Println("cancel a booking")
    case 3, 4:
        fmt.Println("refund status")
    default:
        fmt.Println("talking to an agent...")
    }
}
cancel a booking
  • Go compares key with each case from the top, runs the first case that matches, then leaves the switch.
  • case 3, 4: is a case list: one case, several values.
  • default runs when nothing matches. It's optional, and it can be written anywhere in the switch (it still runs only when no case matches), but by convention it goes last.
  • The cases can be any type that can be compared with ==: ints, strings, bools and so on. The phone menu could just as well be switch city { case "Delhi", "Mumbai": ... }.

Each value only once

package main

import "fmt"

func main() {
    day := 7
    switch day {
    case 6, 7:
        fmt.Println("weekend")
    case 7:
        fmt.Println("sunday")
    }
}
# command-line-arguments
./main.go:10:10: duplicate case 7 (constant of type int) in expression switch
    ./main.go:8:13: previous case

With constant case values, Go refuses duplicates and even points at the previous case, so it's always clear which case runs.

No automatic fallthrough (and the fallthrough keyword)

In C and Java, when a case finishes, execution carries on into the next case unless you write break. Forgetting that break is a famous bug. Go flips the default: each case stops by itself. No break needed.

When you do want to carry on, write the keyword fallthrough as the last statement of a case. An airline: gold members get everything silver gets, and silver gets everything basic gets:

package main

import "fmt"

func main() {
    plan := "gold"
    switch plan {
    case "gold":
        fmt.Println("+ free lounge")
        fallthrough
    case "silver":
        fmt.Println("+ priority boarding")
        fallthrough
    case "basic":
        fmt.Println("+ 15 kg bag")
    }
}
+ free lounge
+ priority boarding
+ 15 kg bag
  • plan is "gold". The gold case ran, fallthrough jumped into the silver block, and silver's fallthrough jumped into basic.
  • fallthrough never checks the next case's value. Silver's case says "silver" and plan is "gold", but its block ran anyway.
  • fallthrough must be the last statement in a case, and the last case can't use it:
package main

import "fmt"

func main() {
    plan := "basic"
    switch plan {
    case "basic":
        fmt.Println("+ 15 kg bag")
        fallthrough
    }
}
# command-line-arguments
./main.go:10:9: cannot fallthrough final case in switch

In real Go code, fallthrough is rare. A case list (case "gold", "silver":) is usually clearer.

break inside a switch

break still exists in a switch: it leaves the switch early.

package main

import "fmt"

func main() {
    item, stock := "chai", 0
    switch item {
    case "chai":
        if stock == 0 {
            fmt.Println("chai is sold out")
            break
        }
        fmt.Println("one chai coming up")
    case "coffee":
        fmt.Println("one coffee coming up")
    }
    fmt.Println("next customer")
}
chai is sold out
next customer

break skipped the rest of the chai case and jumped to the first line after the switch. Watch out: if a switch is inside a loop, break leaves only the switch, not the loop. Episode 8 shows the fix: a labelled break.

switch with no condition (switch true)

Grades: A for 90 and above, B for 75 and above, C for 50 and above. Each check is a range, not one value, so a value switch can't do it. An else if chain works, but it's busy. Go's trick: a switch with nothing after the word switch. Each case is then a full condition, checked top to bottom, and the first true one wins.

package main

import "fmt"

func main() {
    marks := 82
    switch {
    case marks >= 90:
        fmt.Println("grade A")
    case marks >= 75:
        fmt.Println("grade B")
    case marks >= 50:
        fmt.Println("grade C")
    default:
        fmt.Println("try again")
    }
}
grade B

switch { is the same as switch true {: "find the first case whose value equals true". Just like else if, put the strictest condition first: if marks >= 50 came first, 82 would get a C.

Use When
if one condition, or two outcomes
if / else if / else a few conditions of different kinds
switch value { one value compared with many fixed values
switch { many range checks; a neater else if chain

switch with an init statement

Like if, a switch can start with an init statement, and the variable lives only inside the switch:

package main

import "fmt"

func main() {
    switch day := 6; day {
    case 6, 7:
        fmt.Println(day, "is the weekend")
    default:
        fmt.Println(day, "is a weekday")
    }
}
6 is the weekend

With no value after the semicolon (switch units := 250; {), it's a condition-less switch with an init statement, as in the mini project below.

Common mistakes (and the real error messages)

You wrote Real error Fix
if age < 12 fmt.Println(...) syntax error: unexpected name fmt, expected { always use braces
if age { ... } non-boolean condition in if statement if age > 0 { ... }
} then else { on the next line syntax error: unexpected keyword else, expected } } else { on one line
price := age < 12 ? 100 : 200 invalid character U+003F '?' a variable + if
using bill after if bill := ...; ... {} undefined: bill declare it before the if if you need it later
two separate ifs for one choice no error: both blocks run if / else if / else
age >= 12 checked before age >= 60 no error: a senior pays 200 narrowest check first
case 6, 7: ... case 7: duplicate case 7 (constant of type int) in expression switch each value once
fallthrough in the last case cannot fallthrough final case in switch remove it
expecting C-style fall-through without break no error: Go stops after each case fallthrough, or a case list

Mini project: an electricity bill with slabs

Electricity is often billed in slabs: a price per unit that rises as you use more. With made-up rates: the first 100 units cost Rs 3 each, the next 100 cost Rs 5 each, and every unit above 200 costs Rs 8.

package main

import "fmt"

func main() {
    // Mini project: an electricity bill
    switch units := 250; {
    case units <= 100:
        fmt.Println("bill:", units*3)
    case units <= 200:
        fmt.Println("bill:", 100*3+(units-100)*5)
    default:
        fmt.Println("bill:", 100*3+100*5+(units-200)*8)
    }
}
bill: 1200

250 units: 100 × 3 = 300, plus 100 × 5 = 500, plus 50 × 8 = 400, total 1200. The cases go from the smallest slab up, so the first true case is the right slab.

Extension: show the slab and a tip

package main

import "fmt"

func main() {
    for _, units := range []int{80, 150, 250} {
        bill := 0
        switch {
        case units <= 100:
            bill = units * 3
        case units <= 200:
            bill = 100*3 + (units-100)*5
        default:
            bill = 100*3 + 100*5 + (units-200)*8
        }
        if bill > 1000 {
            fmt.Println(units, "units: Rs", bill, "- switch off the AC!")
        } else {
            fmt.Println(units, "units: Rs", bill)
        }
    }
}
80 units: Rs 240
150 units: Rs 550
250 units: Rs 1200 - switch off the AC!

(The for ... range loop runs the same code for three values; it's next episode's topic.)

Practice

  1. Leap year: a year is a leap year if it is divisible by 4, but not by 100, unless it is also divisible by 400. Check 2024, 1900 and 2000.
  2. Write a switch that prints the month name for 1 to 12, and "invalid month" otherwise.
  3. Grade marks with switch {}, then move the marks >= 50 case to the top. What happens to 82?
  4. Add a fourth slab to the electricity bill: above 400 units, Rs 10 per unit.
Solutions and hints
  1. Read the rule as a chain, narrowest first:
package main

import "fmt"

func main() {
    year := 1900
    if year%400 == 0 {
        fmt.Println(year, "is a leap year")
    } else if year%100 == 0 {
        fmt.Println(year, "is not a leap year")
    } else if year%4 == 0 {
        fmt.Println(year, "is a leap year")
    } else {
        fmt.Println(year, "is not a leap year")
    }
}
1900 is not a leap year

Change year to 2024 (leap) and 2000 (leap). The one-line version: year%4 == 0 && (year%100 != 0 || year%400 == 0).

  1. A value switch with a default:
package main

import "fmt"

func main() {
    month := 8
    switch month {
    case 1:
        fmt.Println("January")
    case 2:
        fmt.Println("February")
    case 3:
        fmt.Println("March")
    case 4:
        fmt.Println("April")
    case 5:
        fmt.Println("May")
    case 6:
        fmt.Println("June")
    case 7:
        fmt.Println("July")
    case 8:
        fmt.Println("August")
    case 9:
        fmt.Println("September")
    case 10:
        fmt.Println("October")
    case 11:
        fmt.Println("November")
    case 12:
        fmt.Println("December")
    default:
        fmt.Println("invalid month")
    }
}
August
  1. With marks >= 50 first, 82 matches it first and prints grade C. The first true case wins, so the strictest check must come first.

  2. Add a case before default and rewrite the last slab:

package main

import "fmt"

func main() {
    switch units := 450; {
    case units <= 100:
        fmt.Println("bill:", units*3)
    case units <= 200:
        fmt.Println("bill:", 100*3+(units-100)*5)
    case units <= 400:
        fmt.Println("bill:", 100*3+100*5+(units-200)*8)
    default:
        fmt.Println("bill:", 100*3+100*5+200*8+(units-400)*10)
    }
}
bill: 2900

300 + 500 + 1600 + 500 = 2900.

Quick quiz

What does this print (inside main)?

x := 5
switch {
case x > 1:
    fmt.Print("A")
    fallthrough
case x > 10:
    fmt.Print("B")
case x > 3:
    fmt.Print("C")
}
  • A. A
  • B. AB
  • C. AC
  • D. ABC
Answer

B. AB. x > 1 is the first true case, so A prints. fallthrough jumps into the next block without checking x > 10, so B prints. That case has no fallthrough, so the switch ends: C never runs, even though x > 3 is true.

Interview questions

  • Why does Go require braces on every if, and why must else be on the same line as the closing brace?
  • Can you use an int as an if condition in Go? What error do you get?
  • Why doesn't Go have a ternary operator? What do you write instead?
  • What is the scope of a variable declared in an if init statement? Give a use case.
  • How does Go's switch differ from C's or Java's? Do you need break?
  • What does fallthrough do? Does it check the next case's condition? Where can't it be used?
  • What is switch {} (switch true) and when is it better than else if?
  • What happens with duplicate constant case values?
  • In a switch inside a loop, what does break leave?

Glossary

Term Meaning Example
Control flow the order in which a program's statements run if skips a block
Condition an expression that gives a bool age < 12
bool a value that is only true or false age < 12 is true for 8
Block statements grouped in { } that run together the body of an if
if statement runs a block only when its condition is true if age < 12 { price = 100 }
else the block that runs when the if condition (and every else if) is false } else { ... }
else if adds another condition to the same chain } else if age >= 60 {
if-else chain if, else ifs, else: the first true condition wins, only one block runs the ticket prices
Syntax error code that breaks Go's grammar rules unexpected keyword else
Non-boolean condition using a non-bool value as a condition; an error in Go if age {
Semicolon insertion Go adds an invisible ; at the end of some lines, e.g. after } why else must follow }
Lexer the compiler stage that splits code into words (tokens) it inserts the semicolons
gofmt Go's official code formatter removes ( ) around conditions
Ternary operator cond ? a : b in other languages; Go doesn't have it use a variable + if
Unicode / U+003F the worldwide numbering of characters; U+003F is ? invalid character U+003F '?'
Init statement a short statement before the condition, run first if bill := price * qty; bill > 500 {
Scope the part of the code where a name exists bill exists only in the if chain
Block scope a variable lives only inside the block where it's created undefined: bill outside
switch statement picks one case to run by comparing a value switch key {
case one option in a switch case 2:
Case list one case with several values case 3, 4:
default the case that runs when no other case matches default:
Duplicate case the same constant value in two cases; an error duplicate case 7
Fall-through (C/Java) running on into the next case after one finishes needs break there
fallthrough (Go keyword) jump into the next case's block without checking it gold → silver → basic
Final case the last case of a switch; it can't fallthrough cannot fallthrough final case
break leaves the innermost switch (or loop) immediately "chai is sold out"
Condition-less switch / switch true switch {: each case is a full condition; first true wins grades
Slab a price band that depends on how much you use electricity units 101-200
Expression code that produces a value price * qty
Statement a complete instruction price = 100

Summary

  • if runs a block only when a bool condition is true. Braces always; no brackets needed.
  • else if / else make one chain: checked top to bottom, the first true wins, so put narrow checks first. Write } else { on one line.
  • Go has no ternary operator: use a variable and an if.
  • Init statements (if x := ...; cond {) create helper variables that live only inside the chain.
  • switch value { picks the first matching case; case lists (case 3, 4:), default, no duplicates.
  • Each case stops by itself. fallthrough jumps into the next block without checking it; break leaves the switch early.
  • switch { (switch true) is a clean way to write range checks; switches can have init statements too.

Next episode: loops, the many faces of for. A teacher's punishment, writing one line a hundred times, and you'll make Go repeat work with the only loop it has: for.