为了账号安全,请及时绑定邮箱和手机立即绑定

允许反射从 Go 中的结构中获取未导出的字段

允许反射从 Go 中的结构中获取未导出的字段

Go
牛魔王的故事 2022-06-06 14:50:05
我目前正在使用反射从结构中获取字段并将值作为接口值的一部分返回。我遇到了未导出字段的问题,我希望能够获取未导出的值并将它们与导出的字段一起返回。当我尝试从未导出的字段中获取值时,出现以下错误: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 回答

?
慕侠2389804

TA贡献1719条经验 获得超6个赞

有没有办法通过反射来解决这个问题,所以它返回所有导出和未导出的字段值?

不。

这将违背不出口的目的。


查看完整回答
反对 回复 2022-06-06
  • 1 回答
  • 0 关注
  • 180 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号