doubi6898 2013-03-12 02:09
浏览 95
已采纳

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

The following code gets a pointer to the function hello and prints it:

package main

import "fmt"

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

func hello(a int) {}

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

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

However, if I un-comment the section at the bottom, the compile errors, saying:

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

So I tried:

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

...but that errors with:

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

Ok, so maybe I have to directly refer to original type:

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

Nope:

> ./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)

This sort of works:

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

However, the resulting f2 is a reflect.Method, not a function pointer. :(

What is the appropriate syntax here?

  • 写回答

2条回答 默认 最新

  • duanlou2917 2013-03-12 02:15
    关注

    You can use method expressions, which will return a function that takes the receiver as the first argument.

    f2 := (*x).hello2
    fmt.Printf("%+v
    ", f2)
    
    f2(&x{}, 123)
    

    Otherwise you can just wrap the function call in a function that accepts the x as an argument.

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

    Or that closes over an existing x value.

    val := &x{}
    
    f2 := func() {
        val.hello2(123)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题