我断言指向struct的指针的类型是在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的指针。为什么我不能断言它是一个指针?
发布于 2022-03-30 19:33:40
类型断言用于查找接口中包含的对象的类型。因此,y.(MyInterface)可以工作,因为接口y中包含的对象是一个*MyStruct,并且它实现了MyInterface。但是,*MyInterface不是接口,它是接口的指针,所以您要断言的是y是否是*MyInterface,而不是y是否实现MyInterface。只有在以下情况下才能成功:
var x MyInterface
var y interface{}
y=&x
_, ok := y.(*MyInterface)https://stackoverflow.com/questions/71683078
复制相似问题