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

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

如何通過在 GO 中反映來獲取結構字段的地址

如何通過在 GO 中反映來獲取結構字段的地址

Go
千巷貓影 2023-06-05 17:23:48
我正在編寫將字節流反序列化為對象的代碼,我一直在獲取結構字段的指針?;旧洗a的工作方式如下:它獲取指向結構的指針,然后根據它序列化它的類型,例如。如果它是一個整數,它需要接下來的 4 個字節。棘手的情況是,如果它是一個結構,因為我必須對其所有屬性遞歸運行反序列化,而且我不知道如何獲取其字段的地址以將它們傳遞給反序列化。func Deserialize(objPtr interface{}, b []byte) (bytesRead int) {    // it should be the address of the object    val := reflect.ValueOf(objPtr).Elem()    valPtr := reflect.ValueOf(objPtr)    // check if either the object or *object is Serializable    _, isSerializable := (val.Interface()).(Serializable)    _, bo := (valPtr.Interface()).(Serializable)    isSerializable = isSerializable || bo    // specific type serialization    if isSerializable{        return objPtr.(Serializable).Deserializebyte(b)    }    switch val.Kind() {    case reflect.Uint32, reflect.Int, reflect.Int32:        res := reflect.ValueOf(binary.LittleEndian.Uint32(b[:4]))        valPtr.Set(res)        return 4    case reflect.Uint64, reflect.Int64:        res := reflect.ValueOf(binary.LittleEndian.Uint32(b[:8]))        valPtr.Set(res)        return 8    case reflect.Struct:        n_bytes := 0        for i := 0; i < val.NumField(); i++ {            // stuck in here            valPtr.Elem()            // I don't think the next line works            last_n_bytes := Deserialize(&(valPtr.Elem().Field(i).Interface()), b)            n_bytes += last_n_bytes            b = b[last_n_bytes:]        }        //valPtr.Set(res)        return n_bytes    default:        panic("this panic is for debug, every case should be handled above")        res := val.Bytes()        valPtr.Set(res)        return len(val.Bytes())    }    return 0}
查看完整描述

1 回答

?
夢里花落0921

TA貢獻1772條經驗 獲得超6個贊

使用 reflect API 獲取字段的地址:

last_n_bytes?:=?Deserialize(valPtr.Elem().Field(i).Addr().Interface(),?b)

superint示例發生錯誤,因為應用程序通過反射 API 獲取了未導出字段的地址。這是不允許的,因為它會允許另一個包修改該字段。

這是一個導出字段的工作示例:

type superint struct {

? ? A int

? ? B int

}


func (s *superint) lol() {}


type a interface{ lol() }


func main() {

? ? i := superint{A: 1, B: 9}

? ? valPtr := reflect.ValueOf(&i)

? ? fmt.Printf("%v \n", &i.A)

? ? fmt.Printf("%v \n", valPtr.Elem().Field(0).Addr().Interface())

}


查看完整回答
反對 回復 2023-06-05
  • 1 回答
  • 0 關注
  • 167 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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