dou31797719 2015-01-13 20: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-13 20: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

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部