关于反射的导致panic的一段代码,求解答

```go package main import ( "fmt" "reflect" ) type Student struct { age int name string } func (s *Student)add(age int) { s.age += age; } func main() { s := &Student{20, "jack"} elem := reflect.ValueOf(s).Elem() stype := elem.Type() for i:=0;i
已邀请:

h12 - https://h12.io/about

赞同来自: littlebeast0

两个办法:
1. age -> Age, name -> Name
2.

```go
package main

import (
"fmt"
"reflect"
)

type Student struct {
age int
name string
}

func (s *Student)add(age int) {
s.age += age;
}

func main() {

s := &Student{20, "jack"}
elem := reflect.ValueOf(s).Elem()
stype := elem.Type()

for i:=0;i field := elem.Field(i)
switch field.Kind() {
case reflect.String:
fmt.Printf("%s,%s,%v\n", field.Type(), stype.Field(i).Name, field.String())
case reflect.Int:
fmt.Printf("%s,%s,%v\n", field.Type(), stype.Field(i).Name, field.Int())
}
}
}
```

ioco - 游戏服务器开发

赞同来自: littlebeast0

```go
panic: reflect.Value.Interface: cannot return value obtained from unexported field or method
```
指明了呀,field.Interface()试图读取对象的字段值,但结构体字段是不可导出的,改成大写可导出就行了
另外可以通过 field.CanInterface()判断字段是否可导出。
推荐看你所调用的函数的源码注释
```go
int,Age,20
string,Name,jack
```

要回复问题请先登录注册