Cannot use messageBody (type []byte) as type byte in append ?

411 views
Skip to first unread message

Perry Couprie

unread,
Mar 27, 2021, 9:55:03 PM3/27/21
to golang-nuts
I created the following test code. To isolate the compile error.

Why do i get the error message :

cannot use messageBody (type []byte) as type byte in append.

Greeting from Amsterdam,

Perry 

package main

import (
"encoding/hex"
"fmt"
)

func encodeMessage(messageBody []byte) ([]byte) {

tmp,_ := hex.DecodeString(fmt.Sprintf("AB000300000000007F0100"))

DataResponse := append(tmp, messageBody)

DataResponse[0] = 0xAB

return DataResponse
}

func main() {

}

Kurtis Rader

unread,
Mar 27, 2021, 10:55:31 PM3/27/21
to Perry Couprie, golang-nuts
On Sat, Mar 27, 2021 at 6:55 PM Perry Couprie <perr...@gmail.com> wrote:
I created the following test code. To isolate the compile error.

Why do i get the error message :

cannot use messageBody (type []byte) as type byte in append.

Because the append function takes a variadic list of of elements to append, not a slice. See https://golang.org/ref/spec#Appending_and_copying_slices.

 
func encodeMessage(messageBody []byte) ([]byte) {

tmp,_ := hex.DecodeString(fmt.Sprintf("AB000300000000007F0100"))

DataResponse := append(tmp, messageBody)

Try

     DataResponse := append(tmp, messageBody...)

Although that is probably not the most efficient solution. See, for example, bytes.Buffer.

--
Kurtis Rader
Caretaker of the exceptional canines Junior and Hank
Reply all
Reply to author
Forward
0 new messages