我有一个判空函数
```
func IsEmpty(val interface{}) bool {
if val != nil {
switch v := val.(type) {
case bool:
return false
case string:
return v == ""
case int64, int8, int32, int, int16, float64, float32, uint64, uint8, uint32, uint, uint16:
return v == 0
case time.Time:
return v.IsZero()
case []interface{}:
return len(v) == 0
case []byte:
return len(v) == 0
case []int64:
return len(v) == 0
....
}
}
return true
}
```
case数组类型时,觉得代码很恶心
于是我像下面这样写
```
func IsEmpty(val interface{}) bool {
if val != nil {
switch v := val.(type) {
case bool:
return false
case string:
return v == ""
case int64, int8, int32, int, int16, float64, float32, uint64, uint8, uint32, uint, uint16:
return v == 0
case time.Time:
return v.IsZero()
case []interface{}, []byte, []int64....:
return len(v) == 0
}
}
return true
}
```
但是代码报错了,len() 参数错误。
这个地方比较疑惑,求大佬解释一下,或者有什么更好的实现
推荐使用反射
```go
v := reflect.ValueOf(x)
switch v.Kind() {
case reflect.Bool:
fmt.Printf("bool: %v\n", v.Bool())
case reflect.Int, reflect.Int8, reflect.Int32, reflect.Int64:
fmt.Printf("int: %v\n", v.Int())
case reflect.Uint, reflect.Uint8, reflect.Uint32, reflect.Uint64:
fmt.Printf("int: %v\n", v.Uint())
case reflect.Float32, reflect.Float64:
fmt.Printf("float: %v\n", v.Float())
case reflect.String:
fmt.Printf("string: %v\n", v.String())
case reflect.Slice:
fmt.Printf("slice: len=%d, %v\n", v.Len(), v.Interface())
case reflect.Map:
fmt.Printf("map: %v\n", v.Interface())
case reflect.Chan:
fmt.Printf("chan %v\n", v.Interface())
default:
fmt.Println(x)
}
```
#4
更多评论