go - 在 Go 中连接两个 slice

标签 go append slice variadic-functions

我正在尝试组合 slice [1, 2] 和 slice [3, 4]。如何在 Go 中执行此操作?

我试过了:

append([]int{1,2}, []int{3,4})

但是得到了:

cannot use []int literal (type []int) as type int in append

但是,the documentation似乎表明这是可能的,我错过了什么?

slice = append(slice, anotherSlice...)

最佳答案

在第二个 slice 后添加点:

//                           vvv
append([]int{1,2}, []int{3,4}...)

这就像任何其他可变参数函数一样。

func foo(is ...int) {
    for i := 0; i < len(is); i++ {
        fmt.Println(is[i])
    }
}

func main() {
    foo([]int{9,8,7,6,5}...)
}

关于go - 在 Go 中连接两个 slice ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16248241/

相关文章:

logging - 如何使用golang客户端写入连续写入influxdb

go.mod 在修订时有 post-v0 模块路径 "git.example.com/owner/repo/v3"...?

Kotlin append 到文件

python - 在 Python 中处理字符串中的每一行并将其附加到字典中

go - 从 slice 中删除元素差异 gccgo 与 gc

ios - Swift:我如何在应用程序关闭时保留数据

javascript - 如何让appendchild在单独的行而不是一行中写入html?

python - 在 python 中就地反转列表和使用切片反转有什么区别?

python - 使用 numpy 切片数组索引 numpy 数组

mysql - 如何避免(处理)插入操作的死锁?