First, let me see what it func() (interface{})means the same as func() interface{}, so I will use a shorter form.
Passing function type 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)
}
:
http://play.golang.org/p/JJeww9zNhE
interface{}
doA doB, , interface{}. reflect , func() interface{} :
func Generic(w io.Writer, f interface{}) {
fnValue := reflect.ValueOf(f)
arguments := []reflect.Value{}
fnResults := fnValue.Call(arguments)
result := fnResults[0].Interface()
json.NewEncoder(w).Encode(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)
}
:
http://play.golang.org/p/9M5Gr2HDRN