Appending and Prepending to a Buffer in Golang
When working with buffers in Golang, it's common to append data to the end of the buffer using methods like WriteString. However, in certain scenarios, it may be necessary to write to the beginning of a buffer.
Modifying the Buffer Internally
Since the underlying buf slice in bytes.Buffer is not exported, it's not possible to directly modify the buffer contents. To work around this, you can follow these steps:
buffer.WriteString("B")
s := buffer.String()
buffer.Reset()
buffer.WriteString("A" + s)
This solution effectively prepends data to the buffer.
Example and Output
The following Go Playground code demonstrates this technique:
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()) }
Running the code above yields the output:
AB
In this example, the letter 'A' is prepended to the 'B' initially written to the buffer, resulting in the string "AB."
The above is the detailed content of How can you prepend data to a buffer in Golang?. For more information, please follow other related articles on the PHP Chinese website!