亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

允許反射從 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 關注
  • 206 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號