英文:
Write (or copy) the contents of one bytes.Buffer to another
问题
我有两个bytes.Buffer实例。我想将第二个实例(我们称之为src)的结果复制到第一个实例(dst)中。
显然,在这种情况下io.Copy方法不起作用,因为它需要一个io.Writer接口,而bytes.Buffer没有实现相应的方法。
io.CopyBuffer方法也是一样的情况。
最合适的方法是将一个bytes.Buffer的内容复制到另一个bytes.Buffer中?
英文:
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
得分: 4
使用以下代码将src中的所有字节写入dst:
dst.Write(src.Bytes())
其中,src和dst都是*bytes.Buffer或bytes.Buffer类型的变量。
英文:
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.
答案2
得分: -1
bytes.Buffer实现了io.Writer接口,但只有在它是一个指针时才有效:
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
英文:
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())
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论