As a special case, it is legal to append a string to a byte slice, like this:
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)
}
我做错了什么?
最佳答案
您需要使用“...”作为后缀才能将一个 slice 附加到另一个 slice 。 像这样:
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
关于string - 为什么我不能按照指定的 Go 引用将字符串附加到字节 slice ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27935795/