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

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

為什么binary.Read()不適用于結構?

為什么binary.Read()不適用于結構?

Go
慕妹3146593 2023-07-26 17:38:25
我是 golang 的初學者我的golang版本是1.13我嘗試使用binary如下包package mainimport (    "bytes"    "encoding/binary"    "fmt")type Coordinate struct {    x float64    y float64    z float64}func (self Coordinate) String() string {    return fmt.Sprintf("(%f,%f,%f)", self.x, self.y, self.z)}//not workfunc test() {    var point Coordinate = Coordinate{1, 2, 3}    buf := bytes.Buffer{}    binary.Write(&buf, binary.LittleEndian, &point)    fmt.Println(point)    fmt.Println(buf)    p := new(Coordinate)    //panic: reflect: reflect.flag.mustBeAssignable using value obtained using unexported field    binary.Read(&buf, binary.LittleEndian, p)    fmt.Println(p)}func main() {    test()    println("over")}我收到這樣的錯誤消息:panic: reflect: reflect.flag.mustBeAssignable using value obtained using unexported field我的代碼有什么問題嗎?
查看完整描述

1 回答

?
胡說叔叔

TA貢獻1804條經驗 獲得超8個贊

該錯誤說明了一切:您不能使用未導出的字段。Coordinate更改要導出的字段:


type Coordinate struct {

? ? X float64

? ? Y float64

? ? Z float64

}

然后它就會工作并輸出(在Go Playground上嘗試):


(1.000000,2.000000,3.000000)

{[0 0 0 0 0 0 240 63 0 0 0 0 0 0 0 64 0 0 0 0 0 0 8 64] 0 0}

(1.000000,2.000000,3.000000)

over

也不要遺漏 Go 中的錯誤。binary.Read()binary.Write()返回錯誤,請始終檢查它們,例如:


if err := binary.Write(&buf, binary.LittleEndian, &point); err != nil {

? ? // Handle error, for brevity we just panic here:

? ? panic(err)

}


if err := binary.Read(&buf, binary.LittleEndian, p); err != nil {

? ? // Handle error, for brevity we just panic here:

? ? panic(err)

}


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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