reflect获取结构体方法时遇到的小问题

文章部分引用:

https://blog.csdn.net/qq_35423190/article/details/123554837

在使用reflect包获取函数,并调用时,总出现这个报错:

panic: reflect: call of reflect.Value.Call on zero Value

然后测试发现,只有公有函数(首字母大写的函数)可以通过reflect.MethodByName()函数获取,私有方法是不行的。

package main

import (
	"fmt"
	"reflect"
)

type Student struct {
	Name  string `json:"name" form:"username"`
	Age   int    `json:"age"`
	Score int    `json:"score"`
}

func (s Student) SayHello() {    // 当把SayHello改为sayHello之后就会报错,晕 T^T
	fmt.Println("123456")
}

func main() {
	v := Student{
		Name:  "Hello",
		Age:   3,
		Score: 100,
	}
	a := reflect.ValueOf(v)
	b := a.MethodByName("SayHello")
	b.Call(nil)
}
posted @ 2023-04-07 23:24  喵喵队立大功  阅读(72)  评论(0编辑  收藏  举报