Go1.18泛型:类型参数的零值

1,073 阅读1分钟

我们都知道,Go的类型都有其相应的零值,比如:int为0,string为"",interface为nil。

那当我们有一个类型参数,它的零值是什么?怎么判断它是否为零呢?

// 返回零值
func Get[T any]() T {
    var t T
    return t
}

func Get2[T any]() (t T) {
    return
}

// 判断呢?
func IsZero[T any](t T) bool {
    // if t == 0 { // 可以吗?
    // if t == "" { // 可以吗?
    // if t == nil { // 可以吗?
    // if any(t) == nil { // 可以吗?
    //    return true
    // }
    
    // 如果都不可以,怎么样才行呢?
    
    // 用类型断言,拿到具体类型,再判断零值
    switch tt := any(t).(type) {
    case int:
        return tt == 0
    case string:
        return tt == ""
        
    // more ...
    }
    
    return false
}