doubipeng1336 2017-11-20 07:13
浏览 215
已采纳

如何在Go中将字节数组附加到字节片上[重复]

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>
  • 写回答

2条回答 默认 最新

  • douye8500 2017-11-20 07:23
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?