Điều Kiện if/else và switch
if / else
// Không có dấu () quanh điều kiện
// Bắt buộc {} dù chỉ một dòng
if x > 0 {
fmt.Println("dương")
} else if x < 0 {
fmt.Println("âm")
} else {
fmt.Println("bằng không")
}
if với câu lệnh khởi tạo
// Khai báo biến và kiểm tra trong cùng một dòng
// Biến 'err' chỉ tồn tại trong khối if/else này
if err := doSomething(); err != nil {
fmt.Println("Lỗi:", err)
return
}
// Dùng phổ biến khi làm việc với map
if val, ok := myMap["key"]; ok {
fmt.Println("Tìm thấy:", val)
}
switch
// Go KHÔNG cần break — mỗi case tự dừng
switch os := runtime.GOOS; os {
case "linux":
fmt.Println("Linux")
case "darwin":
fmt.Println("macOS")
case "windows":
fmt.Println("Windows")
default:
fmt.Printf("Khác: %s\n", os)
}
// Nhiều giá trị trong một case
switch day {
case "Thứ 7", "Chủ nhật":
fmt.Println("Cuối tuần!")
default:
fmt.Println("Ngày thường")
}
switch không có biểu thức — thay thế if-else dài
switch {
case diem >= 9.0:
xepLoai = "Xuất sắc"
case diem >= 8.0:
xepLoai = "Giỏi"
case diem >= 6.5:
xepLoai = "Khá"
case diem >= 5.0:
xepLoai = "Trung bình"
default:
xepLoai = "Yếu"
}
fallthrough — chuyển sang case tiếp theo
switch x {
case 1:
fmt.Println("1")
fallthrough // tiếp tục xuống case 2
case 2:
fmt.Println("2") // in cả cái này nếu x == 1
case 3:
fmt.Println("3")
}
Type switch — kiểm tra kiểu động
func describe(i interface{}) {
switch v := i.(type) {
case int:
fmt.Printf("int: %d\n", v)
case string:
fmt.Printf("string: %q\n", v)
case bool:
fmt.Printf("bool: %v\n", v)
default:
fmt.Printf("kiểu khác: %T\n", v)
}
}
describe(42) // int: 42
describe("hello") // string: "hello"
describe(true) // bool: true
example.go
package main
import "fmt"
func xepLoai(diem float64) string {
switch {
case diem >= 9.0:
return "Xuất sắc"
case diem >= 8.0:
return "Giỏi"
case diem >= 6.5:
return "Khá"
case diem >= 5.0:
return "Trung bình"
default:
return "Yếu"
}
}
func moTa(i interface{}) string {
switch v := i.(type) {
case int:
return fmt.Sprintf("Số nguyên: %d", v)
case float64:
return fmt.Sprintf("Số thực: %.2f", v)
case string:
return fmt.Sprintf("Chuỗi: %q", v)
case bool:
return fmt.Sprintf("Logic: %v", v)
default:
return fmt.Sprintf("Không xác định: %T", v)
}
}
func main() {
scores := []float64{9.5, 8.2, 7.0, 6.0, 4.5}
for _, d := range scores {
fmt.Printf("%.1f -> %s\n", d, xepLoai(d))
}
fmt.Println()
values := []interface{}{42, 3.14, "golang", true, []int{1, 2}}
for _, v := range values {
fmt.Println(moTa(v))
}
}