如何在Go中将切片前置到二维切片中?

huangapple go评论62阅读模式
英文:

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]]
}

huangapple
  • 本文由 发表于 2021年12月25日 22:34:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/70480694.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定