package main
import (
"fmt"
"reflect"
)
//AuthRequest struct
type AuthRequest struct {
Id int64
}
func main() {
//AuthRequest auth1
auth1 := AuthRequest{
Id : 1111,
}
//Authrequest auth2
auth2 := AuthRequest{
Id : 2222,
}
//create slice
var sliceModel = make([]AuthRequest, 0)
//put element to slice
sliceModel = append(sliceModel, auth1)
sliceModel = append(sliceModel, auth2)
//Pointer to an array
model := &sliceModel
//How do I get the struct Id field here?
v := reflect.ValueOf(model).Elem()
for j := 0; j < v.NumField(); j++ {
f := v.Field(j)
n := v.Type().Field(j).Name
t := f.Type().Name()
fmt.Printf("Name: %s Kind: %s Type: %s\n", n, f.Kind(), t)
}
}
当我执行上面的代码时,我收到以下错误。
恐慌:反映:在片上调用reflect.Value.NumField值[已恢复]
如何使用反射遍历切片以获取结构AuthRequest中Id字段的值?