为什么我不能按照指定的 Go 引用将字符串附加到字节切片?
Why can't I append string to byte slice as the Go reference specified?
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)
}
我做错了什么?
您需要使用“...”作为后缀才能将一个切片附加到另一个切片。
像这样:
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
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)
}
我做错了什么?
您需要使用“...”作为后缀才能将一个切片附加到另一个切片。 像这样:
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