How to Use bytes.Buffer in Golang

Created
Modified

Examples of Golang bytes.Buffer

The bytes package provides the Buffer type for efficient manipulation of byte slices. A Buffer starts out empty but grows as data of types like string, byte, and []byte are written to it.

Make a main.go file containing the following:

package main

import (
  "bytes"
  "fmt"
)

func main() {

  // New Buffer.
  var b bytes.Buffer

  // Write strings to the Buffer.
  b.WriteString("bytes")
  b.WriteString(".")
  b.WriteString("Buffer")

  // Convert to a string and print it.
  fmt.Println(b.String())

}
$ go run main.go
bytes.Buffer

As the example below shows, a bytes.Buffer variable requires no initialization because its zero value is usable:

package main

import (
  "bytes"
  "fmt"
)

// IntsToStr is like fmt.Sprintf(values) but adds commas.
func IntsToStr(values []int) string {
  var buf bytes.Buffer
  buf.WriteByte('[')
  for i, v := range values {
    if i > 0 {
      buf.WriteString(", ")
    }
    fmt.Fprintf(&buf, "%d", v)
  }
  buf.WriteByte(']')
  return buf.String()
}

func main() {

  fmt.Println(IntsToStr([]int{4, 5, 6, 7}))
  fmt.Println(IntsToStr([]int{}))

}
$ go run main.go
[4, 5, 6, 7]
[]

Reusing bytes.Buffer

You can use code like this:

package main

import (
  "bytes"
  "fmt"
)

var buf bytes.Buffer

func reuseValue(n int, s string) []byte {
  buf.Reset()
  for i := 0; i < n; i++ {
    buf.WriteString(s)
  }

  return buf.Bytes()
}

func main() {

  fmt.Println(string(reuseValue(4, "a")))
  fmt.Println(string(reuseValue(4, "ab")))
  fmt.Println(string(reuseValue(4, "cc")))

}
$ go run main.go
aaaa
abababab
cccccccc

Related Tags

#use# #byte# #buffer#