Coding/Learn/go/go operators and control flow
Go Foundational Course
01.Introduction, Toolchain & Package main
02.Variables, Zero Values, Constants & iota
03.Control Flow: If with Init Statements & Switch
04.The Unified For Loop & Range Iteration
05.Functions, Multiple Return Values & Named Returns
06.Arrays vs Slices: Dynamic Memory & Headers
07.Maps: Key-Value Hash Tables & Safe Access
08.Pointers & Value vs Pointer Semantics
09.Structs, Receiver Methods & Composition
10.Implicit Interfaces & Duck Typing with Typesafety
11.Explicit Error Handling, Wrapping & Inspection
12.Defer, Panic & Recover: Resource Cleanup
13.Strings, Runes & UTF-8 Encoding Internals
14.Goroutines & The M:N Work-Stealing Scheduler
15.Channels: CSP Concurrency & Pipelines
16.Select Statement, Non-Blocking IO & Timeouts
17.Mutexes, RWMutex & Atomic Primitives
18.Context Propagation, Cancellation & Deadlines
19.JSON Serialization, Tags & net/http Routing
20.Capstone: High-Performance Concurrent Microservice Engine
Course Certificate0%

Complete all lessons to earn

LearnControl Flow: If with Init Statements & Switch
3 / 20 0%
Lesson 03 of 20
6 mins read

Control Flow: If with Init Statements & Switch

PreviousNext Lesson
In Plain English

Go features clean conditional branching: if statements support short initialization statements (if x := compute(); x > 0) whose scope is confined to the if/else block. switch statements in Go break automatically without fallthrough and support multiple match expressions per case.

The Mental Model

"An if initialization statement is renting a private locker for the duration of a swim session: the locker key exists while you are at the pool and vanishes automatically once you leave."

Deep Dive: How It Works

If Init Statement: if val, err := lookup(); err == nil confines temporary variables to local scope.

Auto-Break Switch: No manual break required; cases terminate automatically unless fallthrough is specified.

Tagless Switch: switch with no condition expression acts as a cleaner alternative to long if-else-if chains.

Syntax Blueprint

if err := validate(); err != nil {
    return err
}

switch status {
case 200, 201:
    fmt.Println("Success")
default:
    fmt.Println("Error")
}

Scoped initialization statement inside if condition, and multi-value switch matching.

PointCore Rules to Remember

Point star
Scoped Variables: if err := ... limits variable leakage into enclosing function scope.
Point star
No Mandatory Parentheses: Conditions in Go do not use enclosing parentheses (if x > 10 vs if (x > 10)).
Point star
Mandatory Braces: Curly braces {} are mandatory for all if and loop bodies, eliminating dangling else bugs.

Common Beginner Traps & How to Fix Them

Mistake:Placing the opening brace { on a new line after if or func.

Why it happens: Go parser automatically inserts semicolons at line endings.

How to fix: Opening braces must always remain on the same line: if x > 0 {

Pro Tip: Use tagless switch { case x > 100: ... } to replace verbose if-else ladders with elegant, scannable branching.

Live Interactive Example

Hit Run Code to see it live
HTTP Status Dispatcher with Switch
Go 1.22 / Runtime
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Output Console
Click "Run Code" to view the rendered output.
How it works: statusCode 200 matches the first case block and breaks automatically without fallthrough.

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Handle 404 Not Found Code

  • PointSet statusCode to 404.
  • PointRun the program to verify "HTTP Status: Not Found" is printed.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates