string - 为什么我不能按照指定的 Go 引用将字符串附加到字节 slice ?

标签 string go slice

引自 reference of append of Go

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/

相关文章:

java - 在 Java 中解析一个字符串到日期

java - 在 ArrayList<String> 中查找匹配的字符串出现

go - 为什么在 golang 中写入全局 map 时恢复不起作用

go - Reflection.DeepEqual()返回false但 slice 相同

go - 解释预分配 slice 的基准

c++ - 如何将 "std::vector<std::string>"转换为 "const char* array"?

java - 在 Android 中的两个 Activity 之间传递字符串数组时出现 NullPointer

go - 使用 ssh 和交互式 shell 时如何模拟按键

regex - 使用正则表达式进行正则表达式

python - 如何引用 numpy 数组的切片/ View