小编Eri*_*ric的帖子

Go中的动态函数调用

我正在尝试动态调用返回不同类型的函数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
}
Run Code Online (Sandbox Code Playgroud)

我想将函数doAdoB作为参数传递给将执行函数和JSON编码结果的泛型函数.如下:

func Generic(w io.Writer, fn func() (interface {}) {
    result := fn()
    json.NewEncoder(w).Encode(result)
}
Run Code Online (Sandbox Code Playgroud)

但当我这样做时:

Generic(w, doA)
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

cannot use doA (type func() (A)) as type func() (interface {})
Run Code Online (Sandbox Code Playgroud)

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

go first-class-functions

6
推荐指数
1
解决办法
9812
查看次数

标签 统计

first-class-functions ×1

go ×1