dou31797719 2015-01-14 04:18
浏览 56
已采纳

为什么不能按指定的Go引用将字符串附加到字节片上?

Quote from the reference of append of Go

As a special case, it is legal to append a string to a byte slice, like this:
slice = append([]byte("hello "), "world"...)

But I find I can't do that as this snippet:

package main
import "fmt"

func main(){
    a := []byte("hello")
    s := "world"
    a = append(a, s) //*Error*: can't use s(type string) as type byte in append 
    fmt.Printf("%s",a)
}

What have I done wrong?

  • 写回答

1条回答 默认 最新

  • doumeng3345 2015-01-14 04:56
    关注

    You need to use "..." as suffix in order to append a slice to another slice. Like this:

    package main
    import "fmt"
    
    func main(){
        a := []byte("hello")
        s := "world"
        a = append(a, s...) // use "..." as suffice 
        fmt.Printf("%s",a)
    }
    

    You could try it here: http://play.golang.org/p/y_v5To1kiD

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用