C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
String: To convert the Buffer into a string, we can invoke the String() func. This string can then be printed to the console.
Golang program that uses bytes.Buffer, WriteString
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())
}
Output
ABCDEF
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.
Golang program that uses Fprintf with bytes.Buffer
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())
}
Output
A number: 10, a string: bird
[DONE]