我正在尝试动态调用返回不同类型的函数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)
我想将函数doA或doB作为参数传递给将执行函数和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)
有没有办法实现这种动态调用?