Writing to the Beginning of a Buffer in Golang
When working with the bytes.Buffer type in Golang, it's common practice to append data to the buffer using methods like WriteString. However, what if you want to insert data at the beginning of the buffer?
Problem:
You have a bytes.Buffer called buffer and a string s containing data to write. Using the WriteString method, you append s to the end of the buffer. Is it possible to write to the beginning of the buffer instead of appending?
Solution:
While the underlying buf slice of the bytes.Buffer is not directly exported, you can still achieve writing to the beginning of the buffer using the following steps:
Example:
<code class="go">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()) }</code>
Output:
AB
In this example, we first append "B" to the buffer, retrieve the current buffer contents as a string, reset the buffer, and finally write "A" followed by the retrieved string, effectively prepending "A" to the buffer.
The above is the detailed content of How can you insert data at the beginning of a bytes.Buffer in Golang?. For more information, please follow other related articles on the PHP Chinese website!