How to serialize strings to a byte slice? [Solved]


I have a function that serialises my struct but i am not sure how to append to my byte slice for strings. This is what i have:

// Serialize ...
func (data *Data) Serialize(buffer []byte) byte {
 	buffer[0] = NetworkData.Token //header

    uid := data.UID // 4 bytes
    binary.LittleEndian.PutUint32(buffer[1:5], uid)

	copy(buffer[5:42], data.UUID) // 36 bytes

    //username is variable length
    result := []byte(data.Username) //get byte length of string
    buffer = append(buffer[42:], result) // append to buffer
    return 42 + byte(len(result)) // total message size

But i get the error:

  cannot use result (type []byte) as type byte in append

I don’t fully understand why i can’t append this ? Am i doing this wrong or is there simply a better way to go about serialising this data?

From the second parameter onwards, append expects individual slice elements, rather than a second slice.

But that’s no problem, as you can use the ellipsis syntax (three full stops “…”) to expand the second slice into individual elements:

slice1 = append(slice1, slice2...)
1 Like

Ah thank you :slight_smile:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.