我正在嘗試編寫使我能夠將簡單結構編組/解組為字節數組的函數。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)
- 3 回答
- 0 關注
- 205 瀏覽
添加回答
舉報
0/150
提交
取消