gpt4 book ai didi

go - func() 在自定义结构类型上时的接口(interface)转换

转载 作者:行者123 更新时间:2023-12-01 21:17:33 25 4
gpt4 key购买 nike

我有这个完美运行的代码:

package main

import (
"fmt"
)

var funcMap = map[string]interface{}{
"hello": hello,
}

func main() {
callDynamically("hello")
}

func callDynamically(name string) {
funcMap[name].(func())()
}

func hello() {
fmt.Println("hello")
}

但是如果我尝试定义 hello(),我的大脑就会发疯。在我的结构类型上是这样的:
package main

import (
"fmt"
)

type myType struct {
field1 string
field2 string
funcMap map[string]interface{}
}

func main() {
mt := &myType{
field1: "qwe",
field2: "asd",
funcMap: map[string]interface{}{
"hello": (*myType).hello,
},
}

mt.callDynamically("hello")
}

func (mt *myType) callDynamically(name string) {
mt.funcMap[name].(func())()
}

func (mt *myType) hello() {
fmt.Println("hello")
}

https://play.golang.org/p/pPvmaL22_Td

我收到了这个错误:
panic: interface conversion: interface {} is func(*main.myType), not func()

我真的不明白如何调用 func()callDynamically当 my 函数在自定义结构类型上定义时。

有什么帮助吗?

谢谢你。

最佳答案

Go 中的方法只是一个添加了一些语法糖的函数。接收者实际上是函数的第一个参数,因此 (*myType).hello - 来自类型的方法 - 真的是 func(*myType) ;它没有要调用的接收器实例,因此如果不显式提供一个作为函数参数,就无法调用它。这涵盖了in the spec on Method Expressions .

如果您改为从该类型的实例中获取方法,则该参数将已被填充,因此:

foo := &myType{}
fn := foo.hello

这里 fnfunc()因为它已经有一个实例用作接收器。这涵盖了 in the spec on Method Values .

关于go - func() 在自定义结构类型上时的接口(interface)转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62395457/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com