我有一个基础问题,我很难找到答案,因为有很多关于如何使用append函数和spread运算符连接两个“slices”的答案,这些答案错误地使用了“数组”一词。
我是Go语言的新手,并且假设在已知大小的情况下使用定长数组是一个好习惯。然而,我在处理数组时遇到了困难,因为我无法弄清楚如何进行简单的操作,比如拼接。以下是一些代码。
var seven [7]int
five := [5]int{1,2,3,4,5}
two := [2]int{6,7}
//this doesn't work as both the inputs and assignment are the wrong type
seven = append(five,two)
//this doesn't work as the assignment is still the wrong type
seven = append(five[:],two[:])
//this works but I'm not using arrays anymore so may as well use slices everywhere and forget sizing
seven2 := append(five[:],two[:])
据我所见,我可以放弃使用数组,仅使用切片,或者编写循环来显式构建新数组。还有第三种选择吗?
append()
可以进行“原地”执行,则不会分配新数组,而是使用现有的后备数组。 - icza