我试图将切片[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...)

当前回答

我想强调@icza的答案,并简化一下,因为它是一个至关重要的概念。我假设读者对切片很熟悉。

c := append(a, b...)

这是对这个问题的有效回答。 但是,如果你需要在以后的代码中在不同的上下文中使用切片'a'和'c',这不是连接切片的安全方法。

为了解释,让我们不从切片的角度来阅读表达式,而是从底层数组的角度来阅读:

取(底层的)数组'a',并将数组'b'中的元素附加到 它。如果数组'a'有足够的容量包含'b'中的所有元素 c的底层数组不会是一个新数组,它实际上是数组a。基本上,切片'a'将显示len(a)个元素 底层数组a和切片c将显示数组a的len(c) "

Append()不一定创建一个新数组!这可能会导致意想不到的结果。参见Go Playground的例子。

如果你想确保新数组被分配给切片,总是使用make()函数。例如,这里有一些丑陋但足够有效的任务选项。

la := len(a)
c := make([]int, la, la + len(b))
_ = copy(c, a)
c = append(c, b...)

la := len(a)
c := make([]int, la + len(b))
_ = copy(c, a)
_ = copy(c[la:], b)

其他回答

要连接两个切片,

func main() {
    s1 := []int{1, 2, 3}
    s2 := []int{99, 100}
    s1 = append(s1, s2...)

    fmt.Println(s1) // [1 2 3 99 100]
}

将单个值附加到片

func main() {
    s1 :=  []int{1,2,3}
    s1 := append(s1, 4)
    
    fmt.Println(s1) // [1 2 3 4]
}

将多个值追加到一个片

func main() {
    s1 :=  []int{1,2,3}
    s1 = append(s1, 4, 5)
    
    fmt.Println(s1) // [1 2 3 4]
}

并不是反对其他答案,但我发现文档中的简短解释比其中的例子更容易理解:

func append func append(slice []Type, elems ...Type) []Type The append built-in function appends elements to the end of a slice. If it has sufficient capacity, the destination is resliced to accommodate the new elements. If it does not, a new underlying array will be allocated. Append returns the updated slice. It is therefore necessary to store the result of append, often in the variable holding the slice itself: slice = append(slice, elem1, elem2) slice = append(slice, anotherSlice...) As a special case, it is legal to append a string to a byte slice, like this: slice = append([]byte("hello "), "world"...)

Append()函数和展开运算符

可以使用标准golang库中的append方法连接两个片。这类似于变进函数的运算。所以我们需要用…

package main

import (
    "fmt"
)

func main() {
    x := []int{1, 2, 3}
    y := []int{4, 5, 6}
    z := append([]int{}, append(x, y...)...)
    fmt.Println(z)
}

上述代码的输出是:[1 2 3 4 5 6]

在第二片之后加点:

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

我想强调@icza的答案,并简化一下,因为它是一个至关重要的概念。我假设读者对切片很熟悉。

c := append(a, b...)

这是对这个问题的有效回答。 但是,如果你需要在以后的代码中在不同的上下文中使用切片'a'和'c',这不是连接切片的安全方法。

为了解释,让我们不从切片的角度来阅读表达式,而是从底层数组的角度来阅读:

取(底层的)数组'a',并将数组'b'中的元素附加到 它。如果数组'a'有足够的容量包含'b'中的所有元素 c的底层数组不会是一个新数组,它实际上是数组a。基本上,切片'a'将显示len(a)个元素 底层数组a和切片c将显示数组a的len(c) "

Append()不一定创建一个新数组!这可能会导致意想不到的结果。参见Go Playground的例子。

如果你想确保新数组被分配给切片,总是使用make()函数。例如,这里有一些丑陋但足够有效的任务选项。

la := len(a)
c := make([]int, la, la + len(b))
_ = copy(c, a)
c = append(c, b...)

la := len(a)
c := make([]int, la + len(b))
_ = copy(c, a)
_ = copy(c[la:], b)