调用在golang中作为接口变量接收的函数 [英] Invoke a function which is received as an interface variable in golang

查看:297
本文介绍了调用在golang中作为接口变量接收的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与以下代码相似的代码

I have a code which is similar to the following

package main

import "fmt"

func PrintThis(arg string) {
    fmt.Printf("I'm printing %s", arg)
}

func PrintThisAndThat(arg1, arg2 string) {
    fmt.Printf("Now printing %s and %s", arg1, arg2)
}

func Invoke(fn interface{}, args ...string) {
    //fn(args...)
}

func main() {
    Invoke(PrintThis, "foo")
    Invoke(PrintThisAndThat, "foo", "bar")
}

这不是实际的生产代码,但这是简化的版本.

This is not the actual production code, but this is a simplified version.

问题:-如果我取消注释//fn(args...)行,则会出现编译错误prog.go:14: cannot call non-function fn (type interface {})

Question :- If I uncomment the line //fn(args...) I get a compile error prog.go:14: cannot call non-function fn (type interface {})

如何执行通过Invoke()函数作为参数接收的函数?

How do I execute the function which is received as the argument tho the Invoke() function?

实现此目标的正确方法是什么?

What is the right way to achieve this?

推荐答案

您使用 reflect.Value CallSlice 方法进行调用作为一个功能.与所有reflect.Value方法一样,这种恐慌是fn是错误的类型.

You use the Call or CallSlice methods of the reflect.Value to call it as a function. As with all reflect.Value methods, this panics is fn is the wrong type.

func Invoke(fn interface{}, args ...string) {
    v := reflect.ValueOf(fn)
    rargs := make([]reflect.Value, len(args))
    for i, a := range args {
        rargs[i] = reflect.ValueOf(a)
    }
    v.Call(rargs)
}

http://play.golang.org/p/xGmNLDcLL_

这篇关于调用在golang中作为接口变量接收的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆