英文:
How to prepend slice to 2D slice in Go?
问题
var twoDiamArr [][]int
var arr []int
// ....一些代码来向上述切片添加值
// 这个可以工作,并将arr添加到twoDiamArr的末尾:
twoDiamArr := append(twoDiamArr, arr)
// 我期望这个将arr添加到twoDiamArr的开头,但它并不会
twoDiamArr := append(arr, twoDiamArr...)
如何将arr
添加到twoDiamArr
的开头?
英文:
var twoDiamArr [][]int
var arr []int
// .... some code to add values to the above slices
// this works, and adds arr to the end of twoDiamArr:
twoDiamArr := append(twoDiamArr, arr)
// I expected this to add arr to the beginning of twoDiamArr, but it doesn't
twoDiamArr := append(arr, twoDiamArr...)
How can I add arr
to the beginning of twoDiamArr
?
答案1
得分: 1
append()
函数期望将传递给它的第一个参数作为将要返回的值,并将从第二个参数开始的所有内容追加到它后面。
因此,如果你将一个二维数组作为第一个参数传递给append()
,你将从它返回一个二维数组。
表达式append(arr, twoDiamArr...)
则相反,因为你试图将一个二维数组的元素放入另一个一维数组中。结果是你得到一个包含二维数组所有元素的一维数组。
相反,你可以使用一个带有你想要作为第一个元素的值的二维切片字面量。第二个参数中的所有内容将在其后追加。
package main
import "fmt"
func main() {
var twoDimensional = [][]int{{1}, {2}}
var oneDimensional = []int{3}
twoDimensional = append([][]int{oneDimensional}, twoDimensional...)
fmt.Println(twoDimensional)
// 输出 [[3] [1] [2]]
}
英文:
The append()
function expects the first argument passed to it to be the value that will be returned and everything starting from the second argument will be appended to it.
So if you pass a two-dimensional array inside append()
as a first argument, you will have a two-dimensional array returned from it.
The expression append(arr, twoDiamArr...)
is the opposite, because you are trying to put elements of a two-dimensional array inside another one-dimensional. As a result you have one dimensional array with all elements from two-dimensional
Instead, you can use a two-dimensional slice literal with the value you want to have as the first element. Everything spread in the second argument will be appended after it.
package main
import "fmt"
func main() {
var twoDimensional = [][]int{{1}, {2}}
var oneDimensional = []int{3}
twoDimensional = append([][]int{oneDimensional}, twoDimensional...)
fmt.Println(twoDimensional)
// prints [[3] [1] [2]]
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论