为什么我不能像Go参考文档中指定的那样将字符串追加到字节切片中?

huangapple go评论77阅读模式
英文:

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(&quot;hello &quot;), &quot;world&quot;...)

But I find I can't do that as this snippet:

package main
import &quot;fmt&quot;

func main(){
    a := []byte(&quot;hello&quot;)
    s := &quot;world&quot;
    a = append(a, s) //*Error*: can&#39;t use s(type string) as type byte in append 
    fmt.Printf(&quot;%s&quot;,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 &quot;fmt&quot;

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

You could try it here: http://play.golang.org/p/y_v5To1kiD

huangapple
  • 本文由 发表于 2015年1月14日 12:18:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/27935795.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定