Append byte to a byte buffer in golang

huangapple go评论102阅读模式
英文:

Append byte to a byte buffer in golang

问题

我有一个消息字节缓冲区(Buffer),我想在缓冲区的末尾添加一个字节。

我尝试像这样添加:

append(message.Buf, 0xff)
append的第一个参数必须是切片(slice),而现在是*bytes.Buffer类型

append(0xff,message.Buf)
append的第一个参数必须是切片(slice),而现在是未命名的数字类型

我该如何将0xff转换为切片以进行添加?

英文:

I have a message byte Buffer and I would like to append a byte at the end of the Buffer

I tried to append like this:

append(message.Buf, 0xff)
first argument to append must be slice; have *bytes.Buffer

append(0xff,message.Buf)
first argument to append must be slice; have untyped number

How can I make the 0xff as a slice to append?

答案1

得分: 5

你有一个类型为 bytes.Buffer 的缓冲区(具体来说是该类型的指针)。它有一个 Buffer.WriteByte() 方法,你可以直接使用它:

message.Buf.WriteByte(0xff)

内置的 append() 函数是用来向切片 slices 添加值的。bytes.Buffer 不是一个切片,所以你不能在 append() 中使用它(虽然它是使用内部切片实现的,但这是一个你不应该依赖或利用的实现细节)。

英文:

You have a buffer which is of type bytes.Buffer (or more specifically a pointer to that type). It has a Buffer.WriteByte() method, just use that:

message.Buf.WriteByte(0xff)

The builtin append() function which you tried to call is to append values to slices. bytes.Buffer is not a slice, you can't use that with append() (it is implemented using an internal slice, but that is an implementation detail which you should not build on / utilize).

huangapple
  • 本文由 发表于 2017年5月2日 20:38:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/43738105.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定