进入 binary.Read 数据切片得到零结果

Go binary.Read into slice of data gives zero result

我想读取二进制数据并将其写入文件,而我的数据只是切片。编码部分工作正常,但我通过 binary.Read 解码给出的结果为零。我做错了什么?

    data := []int16{1, 2, 3}
    buf := new(bytes.Buffer)
    err := binary.Write(buf, binary.LittleEndian, data)
    if err != nil {
        fmt.Println("binary.Write failed:", err)
    }
    fmt.Println(buf.Bytes())
    // working up to this point

    r := bytes.NewReader(buf.Bytes())
    got := []int16{}
    if err := binary.Read(r, binary.LittleEndian, &got); err != nil {
        fmt.Println("binary.Read failed:")
    }
    fmt.Println("got:", got)

运行 此代码给出

[1 0 2 0 3 0]
got: []

操场link在这里: https://go.dev/play/p/yZOkwXj8BNv

你必须让你的切片和你想从你的缓冲区中读取的一样大。你得到一个空结果,因为 got 的长度为零。

got := make([]int16, buf.Len()/2)
if err := binary.Read(buf, binary.LittleEndian, &got); err != nil {
    fmt.Println("binary.Read failed:")
}

正如 JimB 所说,您可以直接从缓冲区中读取。

另请参阅 binary.Read

的文档

Read reads structured binary data from r into data. Data must be a pointer to a fixed-size value or a slice of fixed-size values. Bytes read from r are decoded using the specified byte order and written to successive fields of the data. [...]