英文:
Why can't I append string to byte slice as the Go reference specified?
问题
从Go的append
参考文档中引用的内容如下:
作为一个特例,将字符串追加到字节切片是合法的,像这样:
slice = append([]byte("hello "), "world"...)
但是我发现我不能像这个片段那样做:
package main
import "fmt"
func main(){
a := []byte("hello")
s := "world"
a = append(a, s) //*错误*:无法将类型为string的s用作append中的byte类型
fmt.Printf("%s",a)
}
我做错了什么?
英文:
Quote from the [reference of append
of Go][1]
> As a special case, it is legal to append a string to a byte slice, like this:
<br>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?
[1]: http://golang.org/pkg/builtin/#append
答案1
得分: 82
你需要使用“...”作为后缀,将一个切片附加到另一个切片上。
像这样:
package main
import "fmt"
func main(){
a := []byte("hello")
s := "world"
a = append(a, s...) // 使用“...”作为后缀
fmt.Printf("%s",a)
}
你可以在这里尝试:http://play.golang.org/p/y_v5To1kiD
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论