Golang Byte Buffer Empty

2018-02-04
I ran into a problem in golang the other day where my bytes.Buffer wasn't storing the bytes I was writing to it. Turns out it's a simple misunderstanding of golang pointers vs golang values.

I had a struct with a single byte.Buffer in it.

type HtmlRewriter struct {
  buf bytes.Buffer
}

func (w HtmlRewriter) Write(p []byte) (n int, err error) {
  return w.buf.Write(p)
}

It's a simple struct which implements the io.Writer interface.

I was using the value instead of a pointer. If you are using a value instead of a pointer in your structs try using a pointer and see if that fixes the issue for you.

type HtmlRewriter struct {
  buf *bytes.Buffer
}

func (w HtmlRewriter) Write(p []byte) (n int, err error) {
  return w.buf.Write(p)
}

I post this here as I couldn't find the answer by googling for 'Golang Byte Buffer Empty' because it's a very specific example of the broader concept of values vs pointers.

Simply put, values are duplicated when passed to functions as parameters or as receivers. This means any changes you made to those values are not applied to the original value.

Read more about it by searching golang pointers vs values.