Trung BìnhGolang iconGolang

Empty interface (any) dùng khi nào?

any (alias interface{}) chấp nhận mọi type, nhưng cần type assertion để dùng value cụ thể.

Go 1.18+ có generics thay thế nhiều use cases.

go
// JSON parsing trả map[string]any
var result map[string]any
json.Unmarshal(data, &result)

// Type assertion để lấy giá trị
func printValue(i any) {
    // safe assertion
    if s, ok := i.(string); ok {
        fmt.Println("string:", s)
        return
    }
    // type switch cho nhiều types
    switch v := i.(type) {
    case int:
        fmt.Println("int:", v)
    case []any:
        fmt.Println("slice length:", len(v))
    default:
        fmt.Printf("unknown: %T\n", v)
    }
}

Dùng cho: generic containers, JSON parsing, function nhận nhiều types.

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

Mở danh sách Golang