donglin7979 2018-10-11 12:08
浏览 149
已采纳

有没有一种方法可以定义一个可以在Golang中运行任何回调函数的函数?

I want to define a function to run a callback function, and the callback function will be uncertain, such as args or returns both are uncertain.

I try this:

package main

import (
    "fmt"
)

func F(callback func(args ...interface{}) interface{}, args ...interface{}) {
    rev := callback(args...)
    fmt.Println(rev)
}

func CB1() {
    fmt.Println("CB1 called")
}

func CB2() bool {
    fmt.Println("CB2 called")
    return false
}

func CB3(s string) {
    fmt.Println("CB3 called")
}

func CB4(s string) bool {
    fmt.Println("CB4 called")
    return false
}

func main() {
    F(CB1)
    F(CB2)
    F(CB3, "xxx")
    F(CB4, "yyy")
}

errors:

./play.go:31:3: cannot use CB1 (type func()) as type func(...interface {}) interface {} in argument to F
./play.go:32:3: cannot use CB2 (type func() bool) as type func(...interface {}) interface {} in argument to F
./play.go:33:3: cannot use CB3 (type func(string)) as type func(...interface {}) interface {} in argument to F
./play.go:34:3: cannot use CB4 (type func(string) bool) as type func(...interface {}) interface {} in argument to F
  • 写回答

1条回答 默认 最新

  • donxbje866688 2018-10-11 12:20
    关注

    You can, but since Go does not support generics, you have to define callback to be of type interface{}.

    To call a function value stored in callback, you may use reflection, namely the Value.Call() method.

    This is how it would look like:

    func F(callback interface{}, args ...interface{}) {
        v := reflect.ValueOf(callback)
        if v.Kind() != reflect.Func {
            panic("not a function")
        }
        vargs := make([]reflect.Value, len(args))
        for i, arg := range args {
            vargs[i] = reflect.ValueOf(arg)
        }
    
        vrets := v.Call(vargs)
    
        fmt.Print("\tReturn values: ")
        for _, vret := range vrets {
            fmt.Print(vret)
        }
        fmt.Println()
    }
    

    With this, the output of your app will be (try it on the Go Playground):

    CB1 called
        Return values: 
    CB2 called
        Return values: false
    CB3 called
        Return values: 
    CB4 called
        Return values: false
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Jenkins+k8s部署slave节点offline
  • ¥15 微信小游戏反编译后,出现找不到分包的情况
  • ¥15 如何实现从tello无人机上获取实时传输的视频流,然后将获取的视频通过yolov5进行检测
  • ¥15 WPF使用Canvas绘制矢量图问题
  • ¥15 用三极管设计一个单管共射放大电路
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'
  • ¥15 nirs_kit中打码怎么看(打码文件是csv格式)
  • ¥15 怎么把多于硬盘空间放到根目录下
  • ¥15 Matlab问题解答有两个问题