Wednesday, 2 November 2016

How to append byte array to slice of bytes in Go




I have a simple bit of code that i am trying to understand, but am struggling to work out how to get it to work properly.



The general idea is i want to pass some data, and convert it into a byte array. Then i want to apply the length of the byte array at the first index of my byte slice, then add the byte array to end of the slice.




This is what it tried:



    var slice []byte
myString := "Hello there"

stringAsByteArray := []byte(myString) //convert my string to byte array


slice[0] = byte(len(stringAsByteArray)) //length of string as byte array


append(slice, stringAsByteArray)


So the idea is the first byte of slice contains the number of len(b) then following on from that, the actual string message as a series of bytes.



But i get:



cannot use stringAsByteArray (type []byte) as type byte in append
append(slice, stringAsByteArray) evaluated but not used


Answer



For example,



package main

import "fmt"

func main() {
myString := "Hello there"

slice := make([]byte, 1, 1+len(myString))
slice[0] = byte(len(myString))
slice = append(slice, myString...)
fmt.Println(slice[0], string(slice[1:]))
}


Output:



11 Hello there


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...