0

I have 2 bytes.Buffer instances. I want to copy the results from the second (let's call it src) to the first one (dst)

Apparently io.Copy method does not work in this case since it requires an io.Writer interface and bytes.Buffer does not implement the corresponding method.

Same goes for the io.CopyBuffer method.

What is the most appropriate way of just copying the contents of one bytes.Buffer to another?

1
  • io.Copy(&dst, &src)
    – colm.anseo
    Oct 29, 2021 at 0:01

2 Answers 2

4

Use

dst.Write(src.Bytes())

to write all of the bytes in src to dst where src and dst are a *bytes.Buffer or a bytes.Buffer.

4
  • In case somebody wants just to create a copy, dst := bytes.NewBuffer(src.Bytes()) will do Jul 28, 2022 at 10:44
  • 1
    @DavidLilue that only copies the slice (view), but does not copy the data. src.Bytes() aliases the underlying storage for src by returning a slice pointing to the same backing array, and bytes.NewBuffer expects to own its argument. This will cause trouble if either src or dst is written to: go.dev/play/p/VvbOGH7Jm0a . Either use dst.Write (which performs a copy(..) on your behalf into dst.Buf) or, if you want to use NewBuffer, use something like dst := bytes.NewBuffer(append([]byte{}, src.Bytes()...)). See also: go.dev/blog/slices-intro
    – Seth P
    Dec 23, 2022 at 16:46
  • One reason that aliasing the storage might appear to work is the bytes.Buffer makes a copy of its data if it grows the backing storage (in turn, unaliasing the array). However, if there's extra capacity in the array, it'll be used before growing. So maybe a more compelling example is: go.dev/play/p/72YxTgeXQnb
    – Seth P
    Dec 23, 2022 at 16:57
  • @SethP thanks for the clarification. The documentation is also clear about it: The new Buffer takes ownership of buf, and the caller should not use buf after this call. buf being the byte slice. Not sure how I missed that. The problem I was solving didn't alter the src slice after copying (just for reading). So for me, it was enough with the shallow copy. Dec 27, 2022 at 10:11
0

bytes.Buffer does implement io.Writer, but only if it is a pointer:

package main
import "bytes"

func main() {
   a := bytes.NewBufferString("hello world")
   b := new(bytes.Buffer)
   b.ReadFrom(a)
   println(b.String())
}

https://godocs.io/bytes#Buffer.Write

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.