一、使用反射调用函数
package main
import (
"fmt"
"reflect"
)
func Tom(i int) int {
return i + 1
}
func main() {
//使用反射调用函数
v := reflect.ValueOf(Tom)
fmt.Println("反射获取到的函数为:",v)
//调用函数
call := v.Call([]reflect.Value{reflect.ValueOf(2)})
fmt.Println("调用函数计算结果后的值",call[0])
}
二、使用反射调用函数性能测试
package helloTest
import (
"reflect"
"testing"
)
//定义一个函数
func too(i int) {
}
//直接调用函数
func BenchmarkTest(b *testing.B) {
for i := 0; i < b.N; i++ {
too(0)
}
b.Log("直接调用函数")
}
//使用反射调用函数
func BenchmarkFunc(b *testing.B) {
v := reflect.ValueOf(too)
b.StopTimer()
b.ResetTimer()
b.StartTimer()
for i := 0; i < b.N; i++ {
v.Call([]reflect.Value{reflect.ValueOf(2)})
}
b.Log("反射调用函数测试")
}