我正在尝试将4096个字节写入os.File,但是它写入了所有容量-您能帮助我理解为什么切片lenbytes的长度大于4096吗?

    // ...
    tempStdin, err := ioutil.TempFile(".", "stdin.txt")
    bytesToBuffer := make([]byte, 4096-1)
    buf := bytes.NewBuffer(bytesToBuffer)
    buf.WriteByte(byte(10))
    pad(1, buf)
    lenbytes := buf.Bytes() // len(lenbytes) is 8191
    if _, err := tempStdin.Write(lenbytes); err != nil {
        panic(err)
    }
}


func pad(siz int, buf *bytes.Buffer) {
    pu := make([]byte, 4096-siz)
    for i := 0; i < 4096-siz; i++ {
        pu[i] = 97
    }
    buf.Write(pu)
}
分析解答

因为此表达式bytesToBuffer := make([]byte, 4096-1)正在将长度和容量都设置为4095的状态下初始化bytesToBuffer

从内置的make文档中:

Slice: The size specifies the length. The capacity of the slice is equal to its length. A second integer argument may be provided to specify a different capacity; [...]

然后bufWriteByteWrite都附加到它。

Write appends the contents of p to the buffer

因此,您最终得到一个切片,其总长度为:

4095(来自make)+1(来自 buf.WriteByte(byte(10)) + 4095(来自buf.Write(pu))= 8191。


改为使用make([]byte, 0, 4096-1)初始化bytesToBuffer。您可以在此去玩上看到它。