Golang 中二进制字节数组的终止指示符?

Terminating indicator for binary byte array in Golang?

在 Golang 中,如果我有二进制数据的字节数组,如果它在更大的数组中,我如何确定实际数据的终止。例如,如果我执行以下操作,读取纯文本文件:

    chunk := make([]byte, 1024)
..read some data into the chunk but only 10 bytes are filled from the file...

然后我可以通过执行以下操作来确定数据的实际大小:

n := bytes.IndexByte(chunk, 0)

当它是纯文本时,n 会给我实际数据的结尾 - 如果数据是二进制的,我该怎么做?

io.Reader's读取函数returns读取的字节数。

然后您可以创建该大小的子切片。 例如:

data := make([]byte,1024)
n, err := reader.Read(arr)
if err != nil {
    // do something with error
} else {
    rightSized := data[:n] 
    // rightSized is []byte of N length now and shares the underlying 
    // backing array so it's both space and time efficient
    // this will contain whatever was read from the reader
}