go - 如何在 go 中获取指向类型化函数的函数指针?

标签 go function-pointers pointer-to-member

以下代码获取指向函数 hello 的指针并打印它:

package main

import "fmt"

type x struct {}
func (self *x) hello2(a int) {}

func hello(a int) {}

func main() {
    f1 := hello
    fmt.Printf("%+v\n", f1)

    // f2 := hello2
    // fmt.Printf("%+v\n", f2)
}

但是,如果我取消注释底部的部分,编译错误会说:

> ./junk.go:14: undefined: hello2

所以我尝试了:

  i := &x{}
  f2 := &i.hello2
  fmt.Printf("%+v\n", f2)

...但是错误是:

> ./junk.go:15: method i.hello2 is not an expression, must be called

好的,所以也许我必须直接引用原始类型:

  f2 := x.hello2
  fmt.Printf("%+v\n", f2)

没有:

> ./junk.go:14: invalid method expression x.hello2 (needs pointer receiver: (*x).hello2)
> ./junk.go:14: x.hello2 undefined (type x has no method hello2)

这类作品:

  i := &x{}
  f2 := reflect.TypeOf(i).Method(0)
  fmt.Printf("%+v\n", f2)

但是,生成的 f2 是一个 reflect.Method,而不是函数指针。 :(

这里合适的语法是什么?

最佳答案

您可以使用方法表达式,它将返回一个将接收者作为第一个参数的函数。

f2 := (*x).hello2
fmt.Printf("%+v\n", f2)

f2(&x{}, 123)

否则,您可以将函数调用包装在接受 x 作为参数的函数中。

f2 := func(val *x) {
    val.hello2(123)
}

或者关闭现有的 x 值。

val := &x{}

f2 := func() {
    val.hello2(123)
}

关于go - 如何在 go 中获取指向类型化函数的函数指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15352089/

相关文章:

戈朗 : remove structs older than 1h from slice

go - 无法进行查询API调用,ResourceNotFoundException:无法对不存在的表执行操作

docker - 使用 docker-compose 安装包

docker - 在 Docker 中构建干净的 Go 应用程序

c++ - 编译器误解了我的代码并向参数添加了额外的 "const"

c++ - 使用函数指针作为成员函数的代理

c++ - 如何通过 val 从 std::deque 中删除函数指针?

c - 函数指针和void指针

c++ - 添加到动态库中的函数指针映射

c++ - 指向成员函数的指针的问题