Nâng CaoGolang iconGolang

Comparable constraint và type sets trong generics Go là gì?

Trong Go generics, constraint là interface xác định tập hợp types (type set) được chấp nhận. comparable là built-in constraint cho phép dùng ==!= — cần thiết khi muốn dùng type parameter làm map key.

go
// comparable — cho phép dùng == và làm map key
func Contains[T comparable](slice []T, item T) bool {
    for _, v := range slice {
        if v == item {
            return true
        }
    }
    return false
}

// Type set constraint — chỉ nhận numeric types
type Number interface {
    int | int8 | int16 | int32 | int64 | float32 | float64
}

func Sum[T Number](nums []T) T {
    var total T
    for _, n := range nums {
        total += n
    }
    return total
}

// Union với ~ (underlying type)
type Integer interface {
    ~int | ~int64  // ~ nghĩa là "kiểu có underlying type là int/int64"
}

// Lồng constraints
type Ordered interface {
    ~int | ~float64 | ~string
}

func Min[T Ordered](a, b T) T {
    if a < b {
        return a
    }
    return b
}

~T cho phép custom types dựa trên underlying type tham gia constraint, ví dụ type MyInt int vẫn thỏa ~int.

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

Mở danh sách Golang