gpt4 book ai didi

go - Go中的动态函数调用

转载 作者:IT王子 更新时间:2023-10-29 01:26:37 26 4
gpt4 key购买 nike

我正在尝试动态调用返回不同类型 struct 的函数。

例如,让我们看下面的代码。

struct A {
Name string
Value int
}

struct B {
Name1 string
Name2 string
Value float
}

func doA() (A) {
// some code returning A
}

func doB() (B) {
// some code returning B
}

我想将函数 doAdoB 作为参数传递给将执行函数并对结果进行 JSON 编码的通用函数。像下面这样:

func Generic(w io.Writer, fn func() (interface {}) {
result := fn()
json.NewEncoder(w).Encode(result)
}

但是当我这样做的时候:

Generic(w, doA)

我收到以下错误:

cannot use doA (type func() (A)) as type func() (interface {})

有没有办法实现这种动态调用?

最佳答案

首先,让我说明一下 func() (interface{})func() interface{} 的含义相同,因此我将使用较短的形式。

传递类型为func() 接口(interface){}的函数

您可以编写一个带有 func() interface{} 参数的通用函数,只要您传递给它的函数具有 func() interface{} 类型>,像这样:

type A struct {
Name string
Value int
}

type B struct {
Name1 string
Name2 string
Value float64
}

func doA() interface{} {
return &A{"Cats", 10}
}

func doB() interface{} {
return &B{"Cats", "Dogs", 10.0}
}

func Generic(w io.Writer, fn func() interface{}) {
result := fn()
json.NewEncoder(w).Encode(result)
}

您可以在现场 playground 中试用此代码:

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

将函数作为 interface{} 类型的参数传递

如果您想编写返回具体类型值的函数 doAdoB,您可以将所选函数作为 interface{} 类型的参数传递。然后你可以使用 reflect package在运行时创建一个func() 接口(interface){}:

func Generic(w io.Writer, f interface{}) {
fnValue := reflect.ValueOf(f) // Make a concrete value.
arguments := []reflect.Value{} // Make an empty argument list.
fnResults := fnValue.Call(arguments) // Assume we have a function. Call it.
result := fnResults[0].Interface() // Get the first result as interface{}.
json.NewEncoder(w).Encode(result) // JSON-encode the result.
}

更简洁:

func Generic(w io.Writer, fn interface{}) {
result := reflect.ValueOf(fn).Call([]reflect.Value{})[0].Interface()
json.NewEncoder(w).Encode(result)
}

完整程序:

主要包

import (
"encoding/json"
"io"
"os"
"reflect"
)

type A struct {
Name string
Value int
}

type B struct {
Name1 string
Name2 string
Value float64
}

func doA() *A {
return &A{"Cats", 10}
}

func doB() *B {
return &B{"Cats", "Dogs", 10.0}
}

func Generic(w io.Writer, fn interface{}) {
result := reflect.ValueOf(fn).Call([]reflect.Value{})[0].Interface()
json.NewEncoder(w).Encode(result)
}

func main() {
Generic(os.Stdout, doA)
Generic(os.Stdout, doB)
}

现场 Playground :

http://play.golang.org/p/9M5Gr2HDRN

关于go - Go中的动态函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32673407/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com