Home  >  Article  >  Backend Development  >  What is the correct way to copy data from io.Reader directly to target bytes.Buffer in golang?

What is the correct way to copy data from io.Reader directly to target bytes.Buffer in golang?

WBOY
WBOYforward
2024-02-05 21:36:08764browse

将数据从 io.Reader 直接复制到 golang 中的目标 bytes.Buffer 的正确方法是什么?

Question content

I have code that wants to copy data from an io.Reader directly to a bytes.Buffer structure which is intended to be kept as a cache in memory. Now I just call io.Copy(dstBytesBuffer, reader). But looking at the io.Copy code, it looks like it's creating a buffer itself, copying the data from the reader into that buffer, and then writing from that buffer to my dstBytesBuffer. Is there a way to skip it and copy it directly from the reader to my destination buffer?


Correct answer


Just use io.Copy(). io.Copy() "Optimized" for multiple use cases. Quoting its documentation:

Copy from src to dst until src reaches EOF or an error occurs. It returns the number of bytes copied and the first error encountered while copying (if any).

Successful copy returns err == nil, not err == EOF. Because Copy is defined to read from src until EOF, it does not treat EOF in Read as an error to report.

If src implements the WriterTo interface, copying is achieved by calling src.WriteTo(dst). Otherwise, if dst implements the ReaderFrom interface, copying is achieved by calling dst.ReadFrom(src).

Don’t know anything about the sourceio.Reader, even if it doesn’t provide an efficient phppcncphpcnWriteTo(dst) method, we definitely know what you are going for The base is bytes.Buffer and it implements io.ReaderFrom because it has a Buffer.ReadFrom() Method reads from the given io.Reader without creating or using additional buffers.

The above is the detailed content of What is the correct way to copy data from io.Reader directly to target bytes.Buffer in golang?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete