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.
Câu lệnh if cho phép bạn phân nhánh code dựa trên điều kiện. Không giống C hoặc Java, Go không yêu cầu dấu ngoặc tròn quanh điều kiện. Mở ngoặc nhọn bắt buộc trên cùng dòng với if.
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.
Go cho phép khởi tạo biến trực tiếp trong điều kiện if. Biến này chỉ có phạm vi bên trong khối if/else. Này là cách Go khuyến khích viết code gọn hơn và tránh ô nhiễm scope.
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).
Go chỉ có một từ khóa vòng lặp: for. Nó có ba biến thể: vòng lặp kiểu C (init; condition; increment), vòng lặp điều kiện (chỉ condition), và vòng lặp vô hạn (không có điều kiện).
1package main23import "fmt"45func main() {6 for i := 0; i < 5; i++ {7 fmt.Println(i)8 }9 // Output: 0 1 2 3 410}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}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}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.
Từ khóa range được dùng trong for để lặp qua slice, array, map, string, hoặc channel. Range trả về index (hoặc key) và giá trị.
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 }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.
Câu lệnh switch so sánh một giá trị với nhiều trường hợp. Không giống C, Go không có fallthrough theo mặc định — chỉ trường hợp khớp được thực thi. Bạn có thể dùng từ khóa fallthrough để rõ ràng cho phép chuyển sang trường hợp tiếp theo.
1package main23import "fmt"45func main() {6 day := 378 switch day {9 case 1:10 fmt.Println("Monday")11 case 2:12 fmt.Println("Tuesday")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.
Từ khóa defer xếp hàng một câu lệnh để được thực thi khi hàm chứa nó thoát ra (ngay cả khi có panic). Các câu lệnh defer được thực thi theo thứ tự LIFO (Last In, First Out) — câu lệnh defer cuối cùng được thêm sẽ chạy đầu tiên. Thường được dùng để dọn dẹp tài nguyên như đóng file hoặc release lock.
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 1A more practical example: using defer to ensure a file closes even if an error occurs.
Ví dụ thực tế hơn: sử dụng defer để đảm bảo đóng file ngay cả khi có lỗi.
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}defer là cách Go khuyến khích quản lý tài nguyên. Nó đảm bảo dọn dẹp ngay cả khi hàm thoát sớm hoặc có panic. Điều này tương tự try-finally hoặc try-with-resources trong Java.
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.
break thoát ra khỏi vòng lặp. continue bỏ qua phần còn lại của lần lặp hiện tại và đi tới lần lặp tiếp theo. goto nhảy tới một nhãn (label) nhưng hiếm khi được dùng vì nó làm code khó hiểu.
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.
Labels cho phép break hoặc continue tác động lên vòng lặp bên ngoài, hữu ích khi có vòng lặp lồng nhau phức tạp.
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
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ì?
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.
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) }
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?
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.