Why can't I append string to byte slice as the Go reference specified?
21,173
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
Comments
-
armnotstrong over 4 years
Quote from the reference of
append
of GoAs 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?