美文网首页
【技术】Golang小tips——interface{}

【技术】Golang小tips——interface{}

作者: 念_夕 | 来源:发表于2018-05-11 21:17 被阅读22次

    interface{} 任意参数传值

    函数的传值中,interface{}是可以传任意参数的
    想当然的写了如下代码测试,然而并不好使

    func main() {
        Any(1)
        Any("222")
    }
    
    func Any(v interface{})  {
         v1:=int(v)
         println(v1)
        
    }
    

    搞了半天发现需要如下处理,不得不佩服go的严谨

    func main() {
        Any(1)
        Any("222")
    }
    func Any(v interface{})  {
    
        if v2, ok := v.(string);ok{
            println(v2)
        }else if v3,ok2:=v.(int);ok2{
            println(v3)
        }
    }
    

    原因如下:
    Conversions are expressions of the form T(x) where T is a type and x is an expression that can be converted to type T.
    A non-constant value x can be converted to type T in any of these cases:

    • x is assignable to T.
    • x's type and T have identical underlying types.
    • x's type and T are unnamed pointer types and their pointer base types have identical
    • underlying types.
    • x's type and T are both integer or floating point types.
    • x's type and T are both complex types.
    • x is an integer or a slice of bytes or runes and T is a string type.
    • x is a string and T is a slice of bytes or runes.

    翻译太渣,各位看官请自行食用

    相关文章

      网友评论

          本文标题:【技术】Golang小tips——interface{}

          本文链接:https://www.haomeiwen.com/subject/vfwgkftx.html