Insertion to the beginning is not possible, see Amd's answer for a "workaround". To overwrite content at the beginning, read on.
Note that the internal byte fragment is Buffer.bufnot exported, but the method Buffer.Bytes()returns a fragment sharing the same substitution array as the internal slice Buffer.buf.
, bytes.Buffer, Bytes.NewBuffer(), , , .
. :
buf := &bytes.Buffer{}
buf.WriteString("Hello World")
fmt.Println("buf:", buf)
buf2 := bytes.NewBuffer(buf.Bytes()[:0])
buf2.WriteString("Gopher")
fmt.Println("buf:", buf)
fmt.Println("buf2:", buf2)
( ):
buf: Hello World
buf: Gopher World
buf2: Gopher
. , , 0 . :
buf := &bytes.Buffer{}
buf.WriteString("Hello World")
fmt.Println("buf:", buf)
buf2 := bytes.NewBuffer(buf.Bytes()[6:6]) // Start after the "Hello"
buf2.WriteString("Gopher")
fmt.Println("buf:", buf)
fmt.Println("buf2:", buf2)
( Go Playground):
buf: Hello World
buf: Hello Gopher
buf2: Gopher
, "" , Buffer.Bytes(), , Buffer, , Buffer , "" ( Buffer):
( , Read, Write, Reset Truncate).