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条)

报告相同问题?

悬赏问题

  • ¥100 关于#VijeoCitect#的问题,如何解决?(标签-ar|关键词-数据类型)
  • ¥30 数字信号处理实验报告
  • ¥15 一个矿井排水监控系统的plc梯形图,求各程序段都是什么意思
  • ¥15 ensp路由器启动不了一直报#
  • ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 数学建模数学建模需要
  • ¥15 已知许多点位,想通过高斯分布来随机选择固定数量的点位怎么改