【问题标题】:Allow reflect to get unexported fields from a struct in Go允许反射从 Go 中的结构中获取未导出的字段
【发布时间】:2020-05-20 14:54:39
【问题描述】:

我目前正在使用反射从结构中获取字段并将值作为接口值的一部分返回。我遇到了未导出字段的问题,我希望能够获取未导出的值并将它们与导出的字段一起返回。当我尝试从未导出的字段中获取值时,出现以下错误:

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
}

当我在未导出字段上的 values 方法中调用 val.Interface() 时出现错误。有没有办法通过反射来解决这个问题,以便它返回所有导出和未导出的字段值?

【问题讨论】:

  • 什么是s.structFields()?
  • 抱歉,错过了。我现在已经添加了
  • Value.Interface(): "如果 Value 是通过访问未导出的结构字段获得的,它会出现恐慌。"您可以使用reflect 遍历未导出的字段,但不能直接获取(或设置)它们的值。

标签: go struct reflect


【解决方案1】:

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

没有。

这会破坏不导出的目的。

【讨论】:

    猜你喜欢
    • 2021-10-04
    • 1970-01-01
    • 2017-07-06
    • 2016-06-17
    • 2014-08-11
    • 2019-02-21
    • 2016-09-13
    • 2010-09-30
    • 1970-01-01
    相关资源
    最近更新 更多