答案基于@ joshlf13的想法和答案,但对我来说似乎更简单。
http://play.golang.org/p/v3zdMGfKy9
package mainimport ( "fmt" "reflect")type ( // Type of function being wrapped sumFuncT func(int, int) (int) // Type of the wrapper function wrappedSumFuncT func(sumFuncT, int, int) (int))// Wrapper of any function// First element of array is the function being wrapped// Other elements are arguments to the functionfunc genericWrapper(in []reflect.Value) []reflect.Value { // this is the place to do something useful in the wrapper return in[0].Call(in[1:])}// Creates wrapper function and sets it to the passed pointer to functionfunc createWrapperFunction(function interface {}) { fn := reflect.ValueOf(function).Elem() v := reflect.MakeFunc(reflect.TypeOf(function).Elem(), genericWrapper) fn.Set(v)}func main() { var wrappedSumFunc wrappedSumFuncT createWrapperFunction(&wrappedSumFunc) // The function being wrapped itself sumFunc := func (a int, b int) int { return a + b } result := wrappedSumFunc(sumFunc, 1, 3) fmt.Printf("Result is %v", result)}


