【问题标题】:How do you get a function pointer to a typed function in go?你如何在 go 中获得指向类型函数的函数指针?
【发布时间】:2013-03-12 02:09:30
【问题描述】:

以下代码获取指向函数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)

但是,生成的f2reflect.Method,而不是函数指针。 :(

这里的适当语法是什么?

【问题讨论】:

    标签: go function-pointers member-function-pointers


    【解决方案1】:

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

    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)
    }
    

    【讨论】:

      【解决方案2】:

      有关 Go 函数调用和闭包的相关阅读:Russ Cox 的“Go 1.1 函数调用”(也详细介绍了 Go1)。

      https://docs.google.com/document/d/1bMwCey-gmqZVTpRax-ESeVuZGmjwbocYs1iHplK-cjo/pub

      【讨论】:

        猜你喜欢
        • 2014-09-19
        • 2020-11-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多