Append []byte arrays

13,905 views
Skip to first unread message

ThePiachu

unread,
Dec 10, 2011, 9:14:41 PM12/10/11
to golang-nuts
I recently tried appending two byte arrays in Go and came across some
odd error. My code is:

one:=make([]byte, 2)
two:=make([]byte, 2)
one[0]=0x00
one[1]=0x01
two[0]=0x02
two[1]=0x03

log.Printf("%X", append(one[:], two[:]))

three:=[]byte{0, 1}
four:=[]byte{2, 3}

five:=append(three, four)

And the errors are:

cannot use four (type []uint8) as type uint8 in append
cannot use two[:] (type []uint8) as type uint8 in append

Which taken into consideration the alleged robustness of Go's slices
should't be a problem:

http://code.google.com/p/go-wiki/wiki/SliceTricks

What am I doing wrong, and how should I go about appending two byte
arrays?

jimmy frasche

unread,
Dec 10, 2011, 9:20:29 PM12/10/11
to ThePiachu, golang-nuts
one = append(one, two...)
the signature of append is, for any fixed T, append([]T, ...T)

Andrew Gerrand

unread,
Dec 10, 2011, 9:22:08 PM12/10/11
to golan...@googlegroups.com
Append adds elements to a slice of elements. You're trying to append a slice to a slice. You can do this by using ... ("dot dot dot").

var s []int{1, 2}
var t []int{3, 4}
s = append(s, t...)
// s == []int{1, 2, 3, 4}

Reply all
Reply to author
Forward
0 new messages