Trung BìnhGolang iconGolang

Type assertion và type switch là gì?

Type assertion lấy giá trị cụ thể từ interface.

  • Type switch xử lý nhiều types một cách gọn gàng.
  • Tương tự instanceof trong JS.
go
var i any = "hello"

// Type assertion — panic nếu sai type
s := i.(string)

// Safe type assertion — không panic
s, ok := i.(string)
if ok {
    fmt.Println(s)
}

// Type switch — idiomatic Go
func describe(i any) {
    switch v := i.(type) {
    case string:
        fmt.Printf("string of length %d\n", len(v))
    case int:
        fmt.Printf("int: %d\n", v)
    case bool:
        fmt.Printf("bool: %v\n", v)
    default:
        fmt.Printf("unknown type: %T\n", v)
    }
}

Xem toàn bộ Golang cùng filter theo level & chủ đề con.

Mở danh sách Golang