Prefix Buffer Writes in Golang
In Golang, the bytes.Buffer is a type designed for efficient string concatenation and manipulation. However, some developers may encounter the need to write to the beginning of a buffer, unlike the built-in helper methods (e.g., WriteString) that only append to the buffer.
Write to Beginning of Buffer
While the underlying buf (internal byte buffer) of bytes.Buffer is not exported, it is possible to manipulate its contents indirectly. Here's how you can achieve it:
buffer.WriteString("B")
s := buffer.String()
buffer.Reset()
buffer.WriteString("A" s)
By concatenating "A" and s, we effectively write "A" at the beginning of the buffer, followed by the original contents.
Example
The following code demonstrates the process:
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
This strategy provides a workaround to write to the beginning of a buffer in Golang despite the limitations of the standard library bytes.Buffer type.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3