引用reference of append of Go年前的话

作为一种特殊情况,将字符串附加到字节片是合法的,如下所示:

但我发现我不能这样做,因为下面的代码片段是这样的:

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

Go相关问答推荐

Golang regexpp:获取带有右括号的单词

gorm插入不支持的数据

Go:嵌入类型不能是类型参数""

在保留额外参数的同时解封YAML

为什么工具链指令在这种情况下没有效果?

+在具有html/模板Golang的Base64中

如何在Golang中使用ECHO服务器实现Socket.IO服务器

Go 切片容量增长率

Go 信号处理程序不处理终端窗口关闭

转换朴素递归硬币问题时的记忆错误

Wire google Inject with multi return from provider 函数

如何仅提取时间作为持续时间

如何编写一个以字符串或错误为参数的通用函数?

Go 泛型:自引用接口约束

如何使用特定的 Go 版本运行 govulncheck?

io.Pipe 使用困难

在 GORM 中,如何在特定时区配置 autoCreateTime 和 autoUpdateTime?

如何正确为 Go 中的值设置多种类型?

是否可以使用按位运算在随机 unicode 字符串中找到重复字符?

如何从 docker-compose 命令运行 2 个不同的命令: