pkaramol
pkaramol

Reputation: 19352

Write (or copy) the contents of one bytes.Buffer to another

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?

Upvotes: 0

Views: 10514

Answers (2)

Zombo
Zombo

Reputation: 1

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

Upvotes: -1

Thundercat
Thundercat

Reputation: 120969

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.

Upvotes: 6

Related Questions