1. 首页
  2. 主题
  3. Go问与答

碰到一个switch case疑惑

windy_ · · 1774 次点击
我有一个判空函数 ``` 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() 参数错误。 这个地方比较疑惑,求大佬解释一下,或者有什么更好的实现
windy_
君子知命不惧,日日自省
写法精简一点。。。
#8
更多评论
你后面的v都应该是 val 啊, v是val的类型,val才是要判断的变量本身。
#1
windy_
君子知命不惧,日日自省
麻烦了解一下switch - type 的语法
#2

用户登录

没有账号?注册

今日阅读排行

    加载中

一周阅读排行

    加载中