Bytes.Buffer
Often we want to build up a long sequence of bytes. With bytes.Buffer
we can write bytes into a single buffer, and then convert to a string
when we are done.
Using bytes.Buffer
is an ideal choice for performance. It can simplify some situations where we want to append many values together.
WriteString
A simple way to append data to a bytes.Buffer
is to call WriteString
. We must pass a string
to this func
. We can call it many times in a loop.
Buffer
into a string
, we can invoke the String()
func
. This string
can then be printed to the console.package main
import (
"bytes"
"fmt"
)
func main() {
// New Buffer.
var b bytes.Buffer
// Write strings to the Buffer.
b.WriteString("ABC")
b.WriteString("DEF")
// Convert to a string and print it.
fmt.Println(b.String())
}ABCDEF
Fprintf
We can use fmt.Fprintf
to append things like numbers to a bytes buffer. A format string
is passed as the second argument of Fprintf
.
Fprintf
will not be ideal—appending bytes directly, with no intermediate format step, would be faster.bytes.Buffer
as the first argument to Fprintf
.package main
import (
"bytes"
"fmt"
)
func main() {
var b bytes.Buffer
// Use Fprintf with Buffer.
fmt.Fprintf(&b, "A number: %d, a string: %v\n", 10, "bird")
b.WriteString("[DONE]")
// Done.
fmt.Println(b.String())
}A number: 10, a string: bird
[DONE]
For appending large amounts of byte
data into a single target buffer, the bytes.Buffer
type is a good choice. We can use it with methods like WriteString
and Fprintf
.