Golang:切片和填充字节数组

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

Golang: Slicing and populating byte arrays

问题

我正在尝试使用golang编写一个数据包协议。由于该协议的长度是固定的,所以在分配内存时,似乎将确切的内存量作为起点是个不错的选择。例如:

packet := make([]byte, 1024)

我不明白的是如何填充该数据包的特定元素。我想做这样的操作:

slice = pointer(packet[512])
slice = []byte("abcdef")

结果是 packet[512:518] == []byte("abcdef")。我阅读的有关数组和切片的文档只说明了如何修改切片中的单个字节,而不是连续的字节序列。是否有一种方法可以实现这个目的?

英文:

I'm trying to write a packet protocol using golang. As the protocol will have a fixed length, it seems like a good starting point to allocate the exact amount of memory. E.g.

packet := make([]byte, 1024)

What I don't understand is how to then populate specific elements of that packet. I want to say something like:-

slice = pointer(packet[512])
slice = []byte("abcdef")

The result being that packet[512:518] == []byte("abcdef"). The docs I've read on Arrays and Slices show how to modify a single byte in a slice but not a contiguous sequence of bytes. Is there a method to do this?

答案1

得分: 8

你不能这样做。我能告诉你最接近的方法是使用复制。请查看:http://play.golang.org/p/PtGJuVgEjc

英文:

You can’t do this. The closest way I can tell is use copy. check: http://play.golang.org/p/PtGJuVgEjc

huangapple
  • 本文由 发表于 2014年7月17日 22:52:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/24806867.html
匿名

发表评论

匿名网友

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

确定