简体   繁体   English

为什么我不能将字符串附加到字节切片作为Go引用指定?

[英]Why can't I append string to byte slice as the Go reference specified?

Quote from the reference of append of Go 引用Go的append引用

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? 我做错了什么?

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 你可以在这里试试: http//play.golang.org/p/y_v5To1kiD

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM