How to Clear a bytes.Buffer in Go

Created
Modified

Using buffer.Reset Function

The buffer.Reset() function resets the buffer to be empty, but it retains the underlying storage for use by future writes. Reset is the same as Truncate(0).

See the following example:

package main

import (
  "bytes"
  "fmt"
)

func main() {

  var b bytes.Buffer // A Buffer needs no initialization.
  b.Write([]byte("Hello "))

  b.ReadByte()
  fmt.Printf("%v\n", b)
  // Clear
  b.Reset()
  fmt.Printf("%v\n", b)
}
{[72 101 108 108 111 32] 1 -1}
{[] 0 0}

Related Tags

#clear# #bytes#