Home > front end >  Write (or copy) the contents of one bytes.Buffer to another
Write (or copy) the contents of one bytes.Buffer to another

Time:10-29

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?

CodePudding user response:

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.

CodePudding user response:

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

  • Related