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)
算啥意思?
有疑问加站长微信联系(非本文作者)

叫做:类型断言,可以理解为类型转换。
规范里面是这里定义的:
“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类型
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
谢谢回答,应该是“任何类型只要它实现了某个interface A的所有方法”吧
嗯,谢谢回答。其实
b.(II)
类型断言是go特有的语法,c++里从了没碰到过这样用的,所以第一次碰到觉得很奇怪是方法,抽象说就是接口
另外,
任何类型只要它实现了某个interface A的所有接口,这个类型的变量就可以转换为A类型
这里的转换是指赋值给A类型的变量或v2 := A(v1)
这样显示转换;类型断言
x.(T)
,是专门针对interface类型的类型检查和转换操作,除了可以做v2 = A(v1)
这样的简单转换能做的,更重要的是做简单转换做不了的, 就像上面嗯,很具体,谢谢