分享
  1. 首页
  2. 文章

Golang中用interface{}接收任何参数与强转

送你一碗大麦茶 · · 25897 次点击 · · 开始浏览
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

函数的传值中,interface{}是可以传任意参数的,就像java的object那样。
下面上我第一次想当然写的 ** 错误 **代码

package main
func main() {
 Any(2)
 Any("666")
}
func Any(v interface{}) {
 v1:=int(v)
 println(v1)
 
}

我只是想它能通过编译而已,因为上面的错误代码并没有任何的语法错误,心里只有666想说,下面是编译的错误提示:
cannot convert v (type interface {}) to type int: need type assertion
正确的代码就可以保证程序不出什么差错。

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

输出如下

2
666

不得不惊叹go的严谨啊。java写类似代码一下就编过去了。

无形之中我喷了java 好多好多,但它毕竟是20年前的语言,比我年纪还大,有些问题是真的没办法,现在基于jvm的kotlin,如果我当时没有放弃android的话,我想我现在的主要工作语言就是它了。

解释一下,为什么Golang有些情况下,强转可以,有点情况下,强转不可以:
其实stack overflow一个国外大神说的很好了,
原话+野生翻译

The reason why you cannot convert an interface typed value are these rules in the referenced specs parts:
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.
    But
    iAreaId := int(val)is not any of the cases 1.-7.

地址:关于interface{}做为参数

野生翻译如下:
我懒得翻了。。。。


有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:送你一碗大麦茶

查看原文:Golang中用interface{}接收任何参数与强转

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

关注微信
25897 次点击
1 回复 | 直到 2019年01月11日 10:21:00
暂无回复
添加一条新回复 (您需要 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传

用户登录

没有账号?注册
(追記) (追記ここまで)

今日阅读排行

    加载中
(追記) (追記ここまで)

一周阅读排行

    加载中

关注我

  • 扫码关注领全套学习资料 关注微信公众号
  • 加入 QQ 群:
    • 192706294(已满)
    • 731990104(已满)
    • 798786647(已满)
    • 729884609(已满)
    • 977810755(已满)
    • 815126783(已满)
    • 812540095(已满)
    • 1006366459(已满)
    • 692541889

  • 关注微信公众号
  • 加入微信群:liuxiaoyan-s,备注入群
  • 也欢迎加入知识星球 Go粉丝们(免费)

给该专栏投稿 写篇新文章

每篇文章有总共有 5 次投稿机会

收入到我管理的专栏 新建专栏