英文:
Is it possible to write on top of a buffer?
问题
你可以使用buff.Write()
方法将内容写入buff
,而不需要创建一个新的缓冲区。以下是示例代码:
buff := bytes.NewBuffer(somebytes)
buff.Write(otherbytes)
这样就可以将otherbytes
写入buff
中,而不会创建一个新的缓冲区。
英文:
buff := bytes.NewBuffer(somebytes)
How to write on top of buff
? Currently I'm creating a new buffer. Is this the right way?
newBuff := bytes.NewBuffer(otherbytes)
newBuff.ReadFrom(buff)
答案1
得分: 4
bytes.NewBuffer()
返回一个 *Buffer
。*Buffer
实现了 io.Writer
(和 io.Reader
),因此您可以通过调用其 Write()
或 WriteString()
方法来简单地向其写入数据。
示例:
somebytes := []byte("abc")
buff := bytes.NewBuffer(somebytes)
buff.Write([]byte("def"))
fmt.Println(buff)
预期输出结果(在 Go Playground 上尝试):
abcdef
如果您想要一个空的缓冲区,您可以简单地创建一个空的 Buffer
结构体(并取其地址):
buff := &bytes.Buffer{}
如果您想要“覆盖”缓冲区的当前内容,您可以使用 Buffer.Reset()
方法或等效的 Buffer.Truncate(0)
调用。
请注意,重置或截断缓冲区将丢弃内容(或仅在 Truncate()
的情况下丢弃部分内容)。但是,后台分配的缓冲区(字节切片)将被保留和重用。
注意:
直接进行您真正想要的操作是不可能的:想象一下,如果您想要在现有内容之前插入一些数据,每次在其前面写入/插入内容时,现有内容都必须被移动。这并不是非常高效的。
相反,您可以在一个 Buffer
中创建主体。一旦完成,您将知道头部将是什么样子。在另一个已经包含头部的 Buffer
中创建头部,当它完成时,将主体(来自第一个 Buffer
)复制(写入)到第二个 Buffer
中。
或者,如果您不需要存储整个数据,您不需要为头部创建第二个 Buffer
。一旦主体准备好,将头部写入输出,然后从 Buffer
中写入主体。
英文:
bytes.NewBuffer()
returns a *Buffer
. *Buffer
implements io.Writer
(and io.Reader
) so you can simply write to it by calling its Write()
or WriteString()
methods.
Example:
somebytes := []byte("abc")
buff := bytes.NewBuffer(somebytes)
buff.Write([]byte("def"))
fmt.Println(buff)
Output as expected (try it on the Go Playground):
abcdef
If you want to start with an empty buffer, you can simply create an empty Buffer
struct (and take its address):
buff := &bytes.Buffer{}
If you want to "overwrite" the current content of the buffer, you can use the Buffer.Reset()
method or the equivalent Buffer.Truncate(0)
call.
Note that resetting or truncating the buffer will throw away the content (or only a part of it in case of Truncate()
. But the allocated buffer (byte slice) in the background is kept and reused.
Note:
What you really want to do is not possible directly: just imagine if you want to insert some data in front of an existing content, the existing content would have to be shifted every time you write / insert something in front of it. This is not really efficient.
Instead create your body in a Buffer
. Once it's done, you will know what your header will be. Create the header in another Buffer
, and when it's done, copy (write) the body (from the first Buffer
) into the second already containing the header.
Or if you don't need to store the whole data, you don't need to create a 2nd Buffer
for the header. Once the body is ready, write the header to your output, and then write the body from the Buffer
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论