bytes.Buffer Examples (WriteString, Fprintf)Use bytes.Buffer to write and store byte data. Call WriteString and fmt.Fprintf.
This page was last reviewed on Dec 1, 2022.
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.
Performance notes. 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.
Detail To convert the 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()) }
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.
Note For performance, using Fprintf will not be ideal—appending bytes directly, with no intermediate format step, would be faster.
Tip We must pass a pointer reference to the 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]
A summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
© 2007-2024 Sam Allen.