英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论