我目前正在使用反射從結(jié)構(gòu)中獲取字段并將值作為接口值的一部分返回。我遇到了未導(dǎo)出字段的問題,我希望能夠獲取未導(dǎo)出的值并將它們與導(dǎo)出的字段一起返回。當(dāng)我嘗試從未導(dǎo)出的字段中獲取值時(shí),出現(xiàn)以下錯(cuò)誤:reflect.Value.Interface:無法返回從未導(dǎo)出的字段或方法獲得的值 [已恢復(fù)]我一直使用https://github.com/fatih/structs作為我的代碼的基礎(chǔ),并希望它與未導(dǎo)出的字段一起使用。// 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}當(dāng)我val.Interface()在未導(dǎo)出的字段上調(diào)用我的 values 方法時(shí)出現(xiàn)錯(cuò)誤。有沒有辦法通過反射來解決這個(gè)問題,所以它返回所有導(dǎo)出和未導(dǎo)出的字段值?
1 回答

慕俠2389804
TA貢獻(xiàn)1719條經(jīng)驗(yàn) 獲得超6個(gè)贊
有沒有辦法通過反射來解決這個(gè)問題,所以它返回所有導(dǎo)出和未導(dǎo)出的字段值?
不。
這將違背不出口的目的。
- 1 回答
- 0 關(guān)注
- 195 瀏覽
添加回答
舉報(bào)
0/150
提交
取消