我是 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)
}
- 1 回答
- 0 關注
- 160 瀏覽
添加回答
舉報
0/150
提交
取消