因此,使用slice表达式,您仅得到一个将容纳完整"行的子集的slice,其类型将相同: [] [] int .如果再次对其进行切片,则只需再次对行的切片进行切片.还请注意,切片表达式中的较高索引是互斥的,因此 a [0:2] 仅具有2行,因此应使用 a [0:3] 或简单地 a [:3] .要获得所需的内容,您必须像这样分别对行进行切片: b:= a [0:3]对于i:=范围b {b [i] = b [i] [0:3]}fmt.Println(b) 这将输出(在游乐场上尝试): [[0 1 2] [1 2 3] [2 3 4]] 或更短: b:= a [:3]对于i,bi:=范围b {b [i] = bi [:3]} I'm getting a surprising result when selecting a 2D sub-slice of a slice.Consider the following 2D int arraya := [][]int{ {0, 1, 2, 3}, {1, 2, 3, 4}, {2, 3, 4, 5}, {3, 4, 5, 6},}To select the top left 3x3 2D slice using ranges I would useb := a[0:2][0:2]I would expect the result to be[[0 1 2] [1 2 3] [2 3 4]]however the second index range doesn't seem to have any effect, and returns the following instead:[[0 1 2 3] [1 2 3 4] [2 3 4 5]]What am I missing? Can you simply not select a sub-slice like this where the dimension > 1 ? 解决方案 You can't do what you want in a single step. Slices and arrays are not 2-dimensional, they are just composed to form a multi-dimensional object. See How is two dimensional array's memory representationSo with a slice expression, you just get a slice that will hold a subset of the "full" rows, and its type will be the same: [][]int. If you slice it again, you just slicing the slice of rows again.Also note that the higher index in a slice expression is exclusive, so a[0:2] will only have 2 rows, so you should use a[0:3] or simply a[:3] instead.To get what you want, you have to slice the rows individually like this:b := a[0:3]for i := range b { b[i] = b[i][0:3]}fmt.Println(b)This will output (try it on the Go Playground):[[0 1 2] [1 2 3] [2 3 4]]Or shorter:b := a[:3]for i, bi := range b { b[i] = bi[:3]} 这篇关于使用go中的范围选择2D切片的2D子切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-20 08:52