This question already has an answer here:
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
</div>
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
make
functionappend
function[]byte
to []byte
you can use spread operator in append
call.append
function