I recently tried appending two byte array slices in Go and came across some odd errors. My code is:
one:=make([]byte, 2)
two:=make([]byte, 2)
one[0]=0x00
one
The Go Programming Language Specification
Appending to and copying slices
The variadic function
appendappends zero or more valuesxtosof typeS, which must be a slice type, and returns the resulting slice, also of typeS. The valuesxare passed to a parameter of type...TwhereTis the element type ofSand the respective parameter passing rules apply.
append(s S, x ...T) S // T is the element type of SPassing arguments to ... parameters
If the final argument is assignable to a slice type
[]T, it may be passed unchanged as the value for a...Tparameter if the argument is followed by....
You need to use []T... for the final argument.
For your example, with the final argument slice type []byte, the argument is followed by ...,
package main
import "fmt"
func main() {
one := make([]byte, 2)
two := make([]byte, 2)
one[0] = 0x00
one[1] = 0x01
two[0] = 0x02
two[1] = 0x03
fmt.Println(append(one[:], two[:]...))
three := []byte{0, 1}
four := []byte{2, 3}
five := append(three, four...)
fmt.Println(five)
}
Playground: https://play.golang.org/p/2jjXDc8_SWT
Output:
[0 1 2 3]
[0 1 2 3]
append() takes a slice of type []T, and then a variable number of values of the type of the slice member T. In other words, if you pass a []uint8 as the slice to append() then it wants every subsequent argument to be a uint8.
The solution to this is to use the slice... syntax for passing a slice in place of a varargs argument. Your code should look like
log.Printf("%X", append(one[:], two[:]...))
and
five:=append(three, four...)