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

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.

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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,872评论 0 10
  • 情感不稳定的人真是太让人难相处,尤其是亲密关系。H君每日不定期的冷漠让我觉得身心俱疲,说不上来的恐惧和疲倦。 如果...
    韩天明z阅读 261评论 0 0
  • 夕阳覆盖了西面的天空,下面高楼大厦鳞次节比,周围有挤满了大小不一的各类建筑。这里是怀着野心和希望的人早就的城市。而...
    Wang子阅读 798评论 0 0
  • “咖啡”一词,我是从高中开始才把它和实物联系在一起的,而在那之前,咖啡对我来说,仅仅是一个书本上的名词而已。 清清...
    西瓜甜甜啦阅读 668评论 17 31
  • 原创 2017-05-21 黄晓杰 混沌研习社 我们不断看书,到处买课,甚至挤时间参加大咖们的线下分享课。每每听完...
    被信任是一种幸福阅读 708评论 0 4

友情链接更多精彩内容