简体   繁体   English

如何断言类型是指向golang中接口的指针

[英]How to assert type is a pointer to an interface in golang

I am asserting that the type of a pointer to a struct is implementing an interface in golang and there is something I don't understand in the code sample below:我断言指向结构的指针类型正在 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")
    }
}

I was expecting to do _, ok:= y.(*MyInterface) since y is a pointer to MyStruct .我期待做_, ok:= y.(*MyInterface)因为y是指向MyStruct的指针。 Why can't I assert it is a pointer?为什么我不能断言它是一个指针?

Type assertion is used to find the type of the object contained in an interface.类型断言用于查找接口中包含的 object 的类型。 So, y.(MyInterface) works, because the object contained in the interface y is a *MyStruct , and it implements MyInterface .所以, y.(MyInterface)有效,因为接口y中包含的 object 是一个*MyStruct ,它实现MyInterface However, *MyInterface is not an interface, it is a pointer to an interface, so what you are asserting is whether y is a *MyInterface , not whether or not y implements MyInterface .但是, *MyInterface不是一个接口,它是一个指向接口的指针,所以你要断言的是y是否是一个*MyInterface ,而不是y是否实现MyInterface This will only be successful if:这只有在以下情况下才会成功:

var x MyInterface
var y interface{}
y=&x
_, ok := y.(*MyInterface)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM