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

huangapple go评论80阅读模式
英文:

How to assert type is a pointer to an interface in golang

问题

我断言,在Go语言中,指向结构体的指针类型实现了一个接口。在下面的代码示例中,有一些我不理解的地方:

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的指针。为什么我不能断言它是一个指针呢?

英文:

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:

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. Why can't I assert it is a pointer?

答案1

得分: 1

类型断言用于查找接口中包含的对象的类型。因此,y.(MyInterface)可以工作,因为接口y中包含的对象是*MyStruct,并且它实现了MyInterface。然而,*MyInterface不是一个接口,它是一个指向接口的指针,所以你断言的是y是否是*MyInterface,而不是y是否实现了MyInterface。只有在以下情况下才会成功:

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

Type assertion is used to find the type of the object contained in an interface. So, y.(MyInterface) works, because the object contained in the interface y is a *MyStruct, and it implements 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. This will only be successful if:

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

huangapple
  • 本文由 发表于 2022年3月31日 03:28:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/71683078.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定