如何断言类型是指向golang中接口的指针
How to assert type is a pointer to an interface in golang
我断言指向结构的指针类型正在 golang 中实现一个接口,但在下面的代码示例中有一些我不明白的地方:
package main
import (
"fmt"
)
type MyStruct struct {
Name string
}
func (m *MyStruct) MyFunc() {
m.Name = "bar"
}
type MyInterface interface {
MyFunc()
}
func main() {
x := &MyStruct{
Name: "foo",
}
var y interface{}
y = x
_, ok := y.(MyInterface)
if !ok {
fmt.Println("Not MyInterface")
} else {
fmt.Println("It is MyInterface")
}
}
我原本希望做 _, ok := y.(*MyInterface)
,因为 y
是指向 MyStruct
的指针。为什么我不能断言它是一个指针?
类型断言用于查找接口中包含的对象的类型。因此,y.(MyInterface)
有效,因为接口 y
中包含的对象是一个 *MyStruct
,它实现了 MyInterface
。但是,*MyInterface
不是一个接口,它是一个指向接口的指针,所以你断言的是 y
是否是一个 *MyInterface
,而不是 y
是否实现MyInterface
。只有在以下情况下才会成功:
var x MyInterface
var y interface{}
y=&x
_, ok := y.(*MyInterface)
我断言指向结构的指针类型正在 golang 中实现一个接口,但在下面的代码示例中有一些我不明白的地方:
package main
import (
"fmt"
)
type MyStruct struct {
Name string
}
func (m *MyStruct) MyFunc() {
m.Name = "bar"
}
type MyInterface interface {
MyFunc()
}
func main() {
x := &MyStruct{
Name: "foo",
}
var y interface{}
y = x
_, ok := y.(MyInterface)
if !ok {
fmt.Println("Not MyInterface")
} else {
fmt.Println("It is MyInterface")
}
}
我原本希望做 _, ok := y.(*MyInterface)
,因为 y
是指向 MyStruct
的指针。为什么我不能断言它是一个指针?
类型断言用于查找接口中包含的对象的类型。因此,y.(MyInterface)
有效,因为接口 y
中包含的对象是一个 *MyStruct
,它实现了 MyInterface
。但是,*MyInterface
不是一个接口,它是一个指向接口的指针,所以你断言的是 y
是否是一个 *MyInterface
,而不是 y
是否实现MyInterface
。只有在以下情况下才会成功:
var x MyInterface
var y interface{}
y=&x
_, ok := y.(*MyInterface)