Skip to content
Skip to content
DocsGo LearningbeginnerControl Flow
Chapter 3 of 14·beginner·6 min read

Control Flow

Luồng Điều Khiển

if/else, for loops, switch, and defer

Hover or tap any paragraph to see Vietnamese translation

if / else Statements

The if statement lets you branch code depending on conditions. Unlike C or Java, Go does not require parentheses around the condition. The opening brace must be on the same line as if.

main.go
1package main23import "fmt"45func main() {6    score := 8578    if score >= 90 {9        fmt.Println("Grade: A")10    } else if score >= 80 {11        fmt.Println("Grade: B")12    } else if score >= 70 {

Go allows variable initialization directly in the if condition. The variable is scoped to the if/else block. This encourages cleaner code and avoids polluting outer scope.

for — The Only Loop Construct

Go has only one loop keyword: for. It has three variants: C-style loop (init; condition; increment), while-style (condition only), and infinite (no condition).

C-style for Loop

main.go
1package main23import "fmt"45func main() {6    for i := 0; i < 5; i++ {7        fmt.Println(i)8    }9    // Output: 0 1 2 3 410}

While-style for Loop

main.go
1package main23import "fmt"45func main() {6    i := 07    for i < 5 {8        fmt.Println(i)9        i++10    }11    // Output: 0 1 2 3 412}

Infinite Loop

main.go
1package main23import "fmt"45func main() {6    i := 07    for {8        if i >= 5 {9            break10        }11        fmt.Println(i)12        i++13    }14    // Output: 0 1 2 3 415}

Range — Iterating Over Collections

The range keyword is used in for loops to iterate over slices, arrays, maps, strings, or channels. Range returns the index (or key) and value.

main.go
1package main23import "fmt"45func main() {6    nums := []int{10, 20, 30}78    // Range over slice — both index and value9    for i, v := range nums {10        fmt.Printf("Index %d: %d11", i, v)12    }

switch — Value Switching

The switch statement compares a value against multiple cases. Unlike C, Go does not fallthrough by default — only the matching case executes. You can explicitly use fallthrough to continue to the next case.

main.go
1package main23import "fmt"45func main() {6    day := 378    switch day {9    case 1:10        fmt.Println("Monday")11    case 2:12        fmt.Println("Tuesday")

defer — Deferred Execution

The defer keyword queues a statement to be executed when the enclosing function returns (even if there is a panic). Deferred statements execute in LIFO order (Last In, First Out) — the last defer added runs first. Commonly used for cleanup like closing files or releasing locks.

main.go
1package main23import "fmt"45func main() {6    fmt.Println("Start")78    defer fmt.Println("Defer 1")9    defer fmt.Println("Defer 2")10    defer fmt.Println("Defer 3")1112    fmt.Println("End")13}1415// Output:16// Start17// End18// Defer 319// Defer 220// Defer 1

A more practical example: using defer to ensure a file closes even if an error occurs.

main.go
1package main23import (4    "fmt"5    "os"6)78func main() {9    f, err := os.Open("file.txt")10    if err != nil {11        fmt.Println("Error:", err)12        return13    }14    defer f.Close() // Guaranteed to close, even if an error occurs later1516    // Read and process file...17    fmt.Println("File opened successfully")18}
Tip
defer is Go's idiomatic way to manage resources. It ensures cleanup happens even if the function exits early or panics. This is similar to try-finally or try-with-resources in Java.

break / continue / goto

break exits a loop. continue skips the rest of the current iteration and goes to the next one. goto jumps to a label, but is rarely used because it makes code harder to understand.

main.go
1package main23import "fmt"45func main() {6    // break example7    for i := 0; i < 10; i++ {8        if i == 5 {9            break10        }11        fmt.Println(i)12    }

Labels allow break or continue to affect outer loops, useful with complex nested loops.

Key Takeaways

Điểm Chính

  • if statements in Go do not require parentheses around the conditionCâu lệnh if trong Go không yêu cầu dấu ngoặc quanh điều kiện
  • for is Go's only loop construct with three variants: C-style, while-style, and infinitefor là vòng lặp duy nhất trong Go với ba biến thể: kiểu C, kiểu while, và vô hạn
  • defer queues a statement to run when the function returns (LIFO order)defer xếp hàng câu lệnh để chạy khi hàm thoát ra (thứ tự LIFO)
  • switch in Go does not fallthrough by default; use fallthrough keyword explicitlyswitch trong Go không fallthrough theo mặc định; dùng từ khóa fallthrough rõ ràng

Practice

Test your understanding of this chapter

Quiz

What is the LIFO execution order in defer statements used for?

Thứ tự LIFO trong các câu lệnh defer được dùng để làm gì?

True or False

In Go, switch statements have fallthrough by default like in C.

Trong Go, câu lệnh switch có fallthrough theo mặc định giống như trong C.

Code Challenge

Complete the for loop using range over a slice

Hoàn thành vòng lặp for sử dụng range trên slice

arr := []int{10, 20, 30}
for , v := range arr {
    fmt.Println(v)
}
Quiz

In Go, can you use parentheses in an if condition?

Trong Go, bạn có thể dùng dấu ngoặc trong điều kiện if không?

True or False

The range keyword in Go can be used to iterate over strings and return runes.

Từ khóa range trong Go có thể lặp qua chuỗi và trả về runes.

Built: 6/25/2026, 3:03:36 PM