Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang: Slicing and populating byte arrays

Tags:

arrays

slice

go

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?

like image 257
Steve Crook Avatar asked Jul 17 '14 14:07

Steve Crook


1 Answers

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

like image 64
chendesheng Avatar answered Sep 21 '22 05:09

chendesheng