Write the beginning of the buffer in the Golang?

I have:

var buffer bytes.Buffer
s := "something to do"
for i := 0; i < 10; i++ {
   buffer.WriteString(s)
}

What is added to the buffer, can it be written to the beginning of the buffer?

+4
source share
2 answers

Since the base is bufnot exported from bytes.Buffer, you can use:

buffer.WriteString("B")
s := buffer.String()
buffer.Reset()
buffer.WriteString("A")
buffer.WriteString(s)

Try the Go Playground :

package main

import (
    "bytes"
    "fmt"
)

func main() {
    var buffer bytes.Buffer
    buffer.WriteString("B")
    s := buffer.String()
    buffer.Reset()
    buffer.WriteString("A" + s)
    fmt.Println(buffer.String())
}

output:

AB
+4
source

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).

+3

Source: https://habr.com/ru/post/1658764/


All Articles