在 Go 中连接两个切片

新手上路,请多包涵

我正在尝试组合切片 [1, 2] 和切片 [3, 4] 。我怎么能在围棋中做到这一点?

我试过了:

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

但得到:

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

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

 slice = append(slice, anotherSlice...)

原文由 Kevin Burke 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 616
2 个回答

在第二个切片后添加点:

 //                           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}...)
}

原文由 user1106925 发布,翻译遵循 CC BY-SA 4.0 许可协议

追加和复制切片

The variadic function append zero or more values x to s of type S , which must be a slice type, and returns the结果切片,也是类型 S 。 The values x are passed to a parameter of type ...T where T is the element type of S and the respective parameter passing rules apply .作为一种特殊情况,append 还接受可分配给类型 []byte 的第一个参数,第二个参数 string 类型后跟 ... 这种形式附加字符串的字节。

>  append(s S, x ...T) S  // T is the element type of S
>
> s0 := []int{0, 0}
> s1 := append(s0, 2)        // append a single element     s1 == []int{0, 0, 2}
> s2 := append(s1, 3, 5, 7)  // append multiple elements    s2 == []int{0, 0, 2, 3, 5, 7}
> s3 := append(s2, s0...)    // append a slice              s3 == []int{0, 0, 2, 3, 5, 7, 0, 0}
>
> ```
>
> [将参数传递给 ... 参数](http://golang.org/ref/spec#Passing_arguments_to_..._parameters)
>
> 如果 `f` 是具有最终参数类型 `...T` 的可变参数,则在函数内该参数等同于 `[]T` 类型的参数。在每次调用 `f` 时,传递给最终参数的参数是类型为 `[]T` 的新切片,其连续元素是实际参数,它们都必须可分配给类型 `T` 。因此,切片的长度是绑定到最终参数的参数数量,并且每个调用站点可能不同。

您的问题的答案是 [Go Programming Language Specification](http://golang.org/ref/spec) 中的示例 `s3 := append(s2, s0...)` 。例如,

s := append([]int{1, 2}, []int{3, 4}…)

”`

原文由 peterSO 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题