Created
September 11, 2021 11:24
-
-
Save donnol/20e60875d5cf6a50f76aecc06f7d5ed6 to your computer and use it in GitHub Desktop.
Go IsZero func
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// IsZeror 可自定义类型实现IsZero方法,用于自定义空值检查,比如要对字符串做TrimSpace操作后再与空值比较 | |
type IsZeror interface { | |
IsZero() bool | |
} | |
// IsZero 判断值v是否为所属类型的零值 | |
// 即使是int和int64两个case也不能合并 | |
func IsZero(v interface{}) bool { | |
switch vv := v.(type) { | |
// 优先检查是否实现了IsZeror接口 | |
case IsZeror: | |
return vv.IsZero() | |
// 自定义类型 | |
case Platform: | |
return vv == 0 | |
case WalletStatus: | |
return vv == 0 | |
// 内置类型 | |
case bool: | |
return !vv | |
case string: | |
return vv == "" | |
case int: | |
return vv == 0 | |
case int8: | |
return vv == 0 | |
case int16: | |
return vv == 0 | |
case int32: | |
return vv == 0 | |
case int64: | |
return vv == 0 | |
case uint: | |
return vv == 0 | |
case uint8: | |
return vv == 0 | |
case uint16: | |
return vv == 0 | |
case uint32: | |
return vv == 0 | |
case uint64: | |
return vv == 0 | |
case float32: | |
return vv == 0.0 | |
case float64: | |
return vv == 0.0 | |
// 最后反射兜底 | |
default: | |
refValue := reflect.ValueOf(v) | |
fmt.Printf("[WARN] use reflect to check if v is zero, please add its type to a case: %s\n", refValue.Type().String()) | |
if refValue.IsZero() { | |
return true | |
} | |
return false | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment