panic: reflect.Value.Interface: cannot return value obtained from unexported field or method

来源:互联网 发布:怎么样抓取精准数据库 编辑:程序博客网 时间:2024/05/16 20:28

原文

go的反射reflect访问struct结构注意问题

type Point struct {    X int    Y string}func main() {    po := Point{3, "ddd"}    s := reflect.ValueOf(&po).Elem()    for i := 0; i < s.NumField(); i++ {        f := s.Field(i)        fmt.Printf(" %s %v \n", f.Type(), f.Interface())    }}输出:int 3 string ddd

但是把Point里面X和Y改成小写的x,y;再执行程序的时候f.Interface会报错:

panic: reflect.Value.Interface: cannot return value obtained from unexported field or method

总结:

go语言里面struct里面变量如果大写则是public,如果是小写则是private的,private的时候通过反射不能获取其值

1 0