You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

binary.Read读取[]byte异常:结构体切片字段为nil却无报错

问题分析与解决

问题原因

binary.Read 处理切片类型时,只会向已分配内存的切片中写入数据。如果传入的切片是 nil(长度为0),它会直接跳过读取操作且不返回错误——因为它认为需要读取的字节数就是切片的长度(0字节),所以不会从buf中读取任何数据,自然test_data.Value始终是nil。

解决方案

在读取Value字段前,先根据已读取的ValueLength值,为test_data.Value分配对应长度的内存空间,再执行binary.Read操作。

修改后的代码

func Test_read_slice(t *testing.T) {
    buf := bytes.NewBuffer([]uint8{0x00, 0x01, 0xB5})
    type Resp struct {
        Status uint8
        ValueLength uint8 /* The length of the value parameter in bytes. */
        Value []uint8 /* The value. */
    }
    test_data := &Resp{}

    if err := binary.Read(buf, binary.LittleEndian, &test_data.Status); err != nil {
        t.Fatalf("Could not read Status: %v", err)
    }
    if err := binary.Read(buf, binary.LittleEndian, &test_data.ValueLength); err != nil {
        t.Fatalf("Could not read ValueLength %v", err)
    }
    // 关键:先根据ValueLength分配切片内存
    test_data.Value = make([]uint8, test_data.ValueLength)
    if err := binary.Read(buf, binary.LittleEndian, test_data.Value); err != nil {
        t.Fatalf("Could not read Value %v", err)
    }
    if test_data.Status != 0 || test_data.ValueLength != 1 || len(test_data.Value) != 1 || test_data.Value[0] != 0xB5 {
        t.Fatalf("Wrong binary values read %+v", test_data)
    }
}

关键改动说明

  • 新增test_data.Value = make([]uint8, test_data.ValueLength):在读取Value前,根据已获取的长度创建对应大小的切片,确保binary.Read有内存空间可以写入数据。
  • 断言中增加了test_data.Value[0] != 0xB5的检查,验证读取的具体值是否正确。

内容的提问来源于stack exchange,提问作者ponkin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 19:02:35