golang接口的这个用法,我到还真是百思不得其解,望解惑

ddxx11223 · 2017-10-12 12:27:09 · 1185 次点击 · 大约8小时之前 开始浏览    置顶
这是一个创建于 2017-10-12 12:27:09 的主题,其中的信息可能已经有所发展或是发生改变。

type I interface{}

type II interface{
    f1()
}

func g2(a II)  {
    fmt.Println("xxx")
}

func h3(b I)  {
    g2(b.(II))
}

type Message struct {
    Name string `json:"msg_name"`
}

func (*Message) f1()  {
}

func main(){
    var m = Message{
        Name: "Alice",
    }
h3(&m)
}

h3函数中的g2(b.(II))这到底是个什么用法?接口强制转换?不像啊,我知道b其实是从I接口动态转过来的*Message类型,那这个b.(II)算啥意思?


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

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

1185 次点击  
加入收藏 微博
7 回复  |  直到 2017-10-13 03:49:00
channel
channel · #1 · 8年之前

叫做:类型断言,可以理解为类型转换。

marlonche
marlonche · #2 · 8年之前

规范里面是这里定义的:

“An interface type specifies a method set called its interface. A variable of interface type can store a value of any type with a method set that is any superset of the interface”

这里的any也包括其它interface类型, 任何类型只要它实现了某个interface A的所有接口,这个类型的变量就可以转换为A类型

marlonche
marlonche · #3 · 8年之前
x.(T)

If T is an interface type, x.(T) asserts that the dynamic type of x implements the interface T.

https://golang.org/ref/spec#Type_assertions

ddxx11223
ddxx11223 · #4 · 8年之前
marlonchemarlonche #2 回复

规范里面是这里定义的: “An interface type specifies a method set called its interface. A variable of interface type can store a value of ***any*** type with a method set that is any superset of the interface” 这里的any也包括其它interface类型, 任何类型只要它实现了某个interface A的所有接口,这个类型的变量就可以转换为A类型

谢谢回答,应该是“任何类型只要它实现了某个interface A的所有方法”吧

ddxx11223
ddxx11223 · #5 · 8年之前
channelchannel #1 回复

叫做:类型断言,可以理解为类型转换。

嗯,谢谢回答。其实b.(II)类型断言是go特有的语法,c++里从了没碰到过这样用的,所以第一次碰到觉得很奇怪

marlonche
marlonche · #6 · 8年之前

是方法,抽象说就是接口

另外,任何类型只要它实现了某个interface A的所有接口,这个类型的变量就可以转换为A类型 这里的转换是指赋值给A类型的变量或v2 := A(v1)这样显示转换;

类型断言x.(T),是专门针对interface类型的类型检查和转换操作,除了可以做v2 = A(v1)这样的简单转换能做的,更重要的是做简单转换做不了的, 就像上面

var m = Message{
    Name: "Alice",
}

var ii II = &m
var i I = I(ii)

var eii II = II(i) //cannot convert i (type I) to type II:I does not implement II (missing f1 method)
var cii II = i.(II)
ddxx11223
ddxx11223 · #7 · 8年之前
marlonchemarlonche #6 回复

是方法,抽象说就是接口 另外,`任何类型只要它实现了某个interface A的所有接口,这个类型的变量就可以转换为A类型` 这里的**转换**是指赋值给A类型的变量或`v2 := A(v1)`这样显示转换; 类型断言`x.(T)`,是专门针对interface类型的类型检查和转换操作,除了可以做`v2 = A(v1)`这样的简单转换能做的,更重要的是做简单转换做不了的, 就像上面 var m = Message{ Name: "Alice", } var ii II = &m var i I = I(ii) var eii II = II(i) //cannot convert i (type I) to type II:I does not implement II (missing f1 method) var cii II = i.(II)

嗯,很具体,谢谢

添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传