我目前正在使用反射從結構中獲取字段并將值作為接口值的一部分返回。我遇到了未導出字段的問題,我希望能夠獲取未導出的值并將它們與導出的字段一起返回。當我嘗試從未導出的字段中獲取值時,出現以下錯誤:reflect.Value.Interface:無法返回從未導出的字段或方法獲得的值 [已恢復]我一直使用https://github.com/fatih/structs作為我的代碼的基礎,并希望它與未導出的字段一起使用。// Values returns us the structs values ready to be converted into our repeatable digest.func (s *StructWrapper) Values() []interface{} { fields := s.structFields() var t []interface{} for _, field := range fields { val := s.value.FieldByName(field.Name) if IsStruct(val.Interface()) { // look out for embedded structs, and convert them to a // []interface{} to be added to the final values slice t = append(t, Values(val.Interface())...) } else { t = append(t, val.Interface()) } } return t}// Values converts the given struct to a []interface{}. For more info refer to// StructWrapper types Values() method. It panics if s's kind is not struct.func Values(s interface{}) []interface{} { return New(s).Values()}// New returns a new *StructWrapper with the struct s. It panics if the s's kind is// not struct.func New(s interface{}) *StructWrapper { return &StructWrapper{ raw: s, value: strctVal(s), }}func strctVal(s interface{}) reflect.Value { v := reflect.ValueOf(s) // if pointer get the underlying element≤ for v.Kind() == reflect.Ptr { v = v.Elem() } if v.Kind() != reflect.Struct { panic("not struct") } return v}// structFields returns the exported struct fields for a given s struct. This// is a convenient helper method to avoid duplicate code in some of the// functions.func (s *StructWrapper) structFields() []reflect.StructField { t := s.value.Type() var f []reflect.StructField for i := 0; i < t.NumField(); i++ { field := t.Field(i) f = append(f, field) } return f}當我val.Interface()在未導出的字段上調用我的 values 方法時出現錯誤。有沒有辦法通過反射來解決這個問題,所以它返回所有導出和未導出的字段值?
- 1 回答
- 0 關注
- 206 瀏覽
添加回答
舉報
0/150
提交
取消