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

标签 go struct reflect

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

reflect.Value.Interface: cannot return value obtained from unexported field or method [recovered]



我一直在使用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() 时收到错误消息在我的未导出字段上的值方法中。有没有办法通过反射来解决这个问题,所以它返回所有导出和未导出的字段值?

最佳答案

Is there a way around this with reflect so it returns all exported and unexported field values?



不。

这将违背不导出的目的。

关于go - 允许反射从 Go 中的结构中获取未导出的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61916224/

相关文章:

go - 如何合并两个相同结构类型的 Go 值?

opengl - 调用 gl.GenVertexArrays 时出现内存错误

c# - 在 C# 中使用接口(interface)时的值与引用类型

c - 改进了在结构指针内为结构双指针动态分配内存的方法

pointers - 反射结构字段。使用标志指针值设置

pointers - Go中的通用解码

go - 如何检测 TCPConn 是否存活

mongodb - mongoimport 在 mac Sierra 10.12.2 上抛出随机 MSpanList_Insert 错误

http - 对每个请求使用不同的代理

从 argv、树 trie 复制时核心被转储