首先,需要导入reflect包。然后,可以使用reflect.TypeOf()函数来获取函数的类型,再通过Type的Name()方法获取函数的名称。 以下是一个示例代码: 代码语言:txt 复制 package main import ( "fmt" "reflect" ) func main() { functionName := getFunctionName(myFunction) fmt.Println(functionName) } func myFunct...
package main import ("fmt""reflect")func main() { // 一个简单的函数,接受一个字符串并打印 myFunction := func(s string) { fmt.Println("Hello, " + s)} // 字符串表示的函数名 functionName := "myFunction"// 通过反射获取函数 functionValue := reflect.ValueOf(myFunction)1/ 2 ...
fmt.Println("name:", GetFunctionName(foo)) // runtime/debug.FreeOSMemory fmt.Println(GetFunctionName(debug.FreeOSMemory)) // FreeOSMemory fmt.Println(GetFunctionName(debug.FreeOSMemory, '.')) // FreeOSMemory fmt.Println(GetFunctionName(debug.FreeOSMemory, '/', '.')) }...
type=%T\n",rTyp,rTyp)rVal:=reflect.ValueOf(b)fmt.Printf("rVal=%v,type=%T\n",rVal,rVal)iVal:=rVal.Interface()stu2:=iVal.(student)fmt.Printf("stu2=%v,type=%T\n",stu2,stu2)fmt.Printf("name:%v,age:%v",stu2.name,stu2.age)}funcmain(){stu:=student{name:"tom",age:...
rVal :=reflect.ValueOf(b) fmt.Printf("rVal=%v,type=%T\n", rVal, rVal) iVal :=rVal.Interface() stu2 :=iVal.(student) fmt.Printf("stu2=%v,type=%T\n", stu2, stu2) fmt.Printf("name:%v,age:%v", stu2.name, stu2.age) ...
你可以使用反射来获取变量的类型: var t := reflect.Typeof(v)。返回值是一个reflect.Type类型。该值有很多定义好的方法可以使用。 Name() 返回类型的名称。 但是像切片或指针是没有类型名称的,只能返回空字符串。 Kind() Kind有slice, map , pointer指针,struct, interface, string , Array, Function, int...
pointerValue = reflect.ValueOf(age) newValue = pointerValue.Elem() // 如果非指针,直接panic: reflect: call of reflect.Value.Elem on int Value } 3.方法调用。Method和MethodByName可以获取到具体的方法,Call可以实现方法调用。 // Method returns a function value corresponding to v's i'th method....
func printFunctionDetails(f reflect.Value) { fmt.Printf("Function Name: %s\n", f.Type().Name()) fmt.Printf("Function Type: %s\n", f.Type()) } 在上述代码中,我们首先通过`f.Type().Name()`获取函数的名称,然后通过`f.Type()`获取函数的类型,并将这些信息打印出来。现在,我们已经了解了获取...
func Call(m map[string]interface{}, name string, params ... interface{}) (result []reflect.Value, err error) { f = reflect.ValueOf(m[name]) iflen(params) != f.Type().NumIn() { err = errors.New("The number of params is not adapted.") ...
// 自定义一个 MyInt 类型typeMyIntint// 声明一个空结构体typeMyStructstruct{}funcmain(){// 定义一个变量varaMyInttypeOfA:=reflect.TypeOf(a)// 显示反射类型对象的名称和种类fmt.Println(typeOfA.Name(),typeOfA.Kind())// MyInt int// 获取结构体实例的反射类型对象typeOfB:=reflect.TypeOf(MySt...