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

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

使用反射將字節讀入結構

使用反射將字節讀入結構

Go
HUWWW 2021-04-25 15:08:27
我正在嘗試編寫使我能夠將簡單結構編組/解組為字節數組的函數。Marshal在#go-nuts的好心人的幫助下,我已經成功地寫作,但是我在寫作方面遇到了麻煩Unmarshal。// Unmarshal unpacks the binary data and stores it in the packet using// reflection.func Unmarshal(b []byte, t reflect.Type) (pkt interface{}, err error) {    buf := bytes.NewBuffer(b)    p := reflect.New(t)    v := reflect.ValueOf(p)    for i := 0; i < t.NumField(); i++ {        f := v.Field(i)        switch f.Kind() {        case reflect.String:            // length of string            var l int16            var e error            e = binary.Read(buf, binary.BigEndian, &l)            if e != nil {                err = e                return            }            // read length-of-string bytes from the buffer            raw := make([]byte, l)            _, e = buf.Read(raw)            if e != nil {                err = e                return            }            // convert the bytes to a string            f.SetString(bytes.NewBuffer(raw).String())        default:            e := binary.Read(buf, binary.BigEndian, f.Addr())            if e != nil {                err = e                return            }        }    }    pkt = p    return}上面代碼的問題是,對f.Addr()尾部的調用顯然試圖獲取不可尋址值的地址。如果有替代解決方案,我也將不勝感激。無論哪種方式,任何幫助將不勝感激。
查看完整描述

3 回答

?
慕田峪4524236

TA貢獻1875條經驗 獲得超5個贊

我認為你應該使用

v := p.Elem()   // Get the value that 'p' points to

代替

v := reflect.ValueOf(p)


查看完整回答
反對 回復 2021-05-10
  • 3 回答
  • 0 關注
  • 205 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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