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

时间:2015-01-14 04:18:53

标签: string go slice

来自reference of append of Go

的引用
  

作为一种特殊情况,将字符串附加到字节切片是合法的,如下所示:   
slice = append([]byte("hello "), "world"...)

但我觉得我不能这样做,因为这个片段:

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

我做错了什么?

1 个答案:

答案 0 :(得分:48)

你需要使用" ..."作为后缀,以便将切片附加到另一个切片。 像这样:

package main
import "fmt"

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

你可以在这里试试:http://play.golang.org/p/y_v5To1kiD