我试图将切片[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...)
我试图将切片[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...)
当前回答
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]
其他回答
Append ([]int{1,2}, []int{3,4}…)将工作。传递参数给…参数。
如果f是可变的,最终参数p类型为…T,那么在f内p的类型等价于类型[]T。
如果对p调用f时没有实际参数,则传递给p的值为nil。
否则,传递的值是一个类型为[]T的新切片,其中新的底层数组的连续元素是实际的参数,这些元素都必须可分配给T。因此,切片的长度和容量是绑定到p的参数的数量,并且可能因每个调用站点而不同。
给定函数和调用
func Greeting(prefix string, who ...string)
Greeting("nobody")
Greeting("hello:", "Joe", "Anna", "Eileen")
要连接两个切片,
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]
}
在第二片之后加点:
// 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}...)
}
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]
似乎是泛型的完美用途(如果使用1.18或更高版本)。
func concat[T any](first []T, second []T) []T {
n := len(first);
return append(first[:n:n], second...);
}