从多维数组中创建多维切片的结果与预期不符。

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

Making multidimensional slice from multidimensional array does not work as expected

问题

我正在尝试从多维数组创建一个多维切片,但出现了一些奇怪的情况(至少对我来说是奇怪的)。我创建了一个多维数组 ma,并从中创建了三个切片 s1s2s3。下面的代码展示了这个过程:

package main

import (
	"fmt"
)

func main() {
	var ma [4][3]int32 = [4][3]int32{
		{10, 20, 30},
		{50, 60, 70},
		{80, 90, 100},
		{110, 120, 130},
	}

	var s1 [][3]int32 = ma[:]       // 预期的结果

	var s2 [][3]int32 = ma[:][:]	// ????

	var s3 [][]int32 = ma[0:2][0:2]	// ????
}

var s1 [][3]int32 = ma[:] 的行为符合预期。ma[:] 创建了一个 [3]int32 数组的切片,因此我们有一个底层数组,每个元素的类型都是 [3]int32 数组。对我来说,这是完全符合预期的行为。

问题出现在定义 s1 和 s2 时。它们的行为与我预期的不同。var s2 [][3]int32 = ma[:][:] 的结果与 var s1 [][3]int32 = ma[:] 相同。我期望它创建一个切片的切片,而不是一个数组的切片。这是如何可能的?这两者怎么会得到相同的结果?

此外,我期望 var s3 [][]int32 = ma[0:2][0:2] 也会创建一个切片的切片。但实际上它给出了错误信息:"cannot use ma[0:2][0:2] (value of type [][3]int32) as [][]int32 value in variable declaration compiler"。所以,用 ma[0:2][0:2] 得到的类型是 [][3]int32,而不是 [][]int32。这是怎么回事?

希望我已经解释清楚了我不明白的地方。

英文:

I'm trying to create a multidimensional slice from a multidimensional array and some strange things are happening (at least for me). I created a multidimensional array ma and made three slices s1, s2, s3 from it. The code below shows this:

package main

import (
	"fmt"
)

func main() {
	var ma [4][3]int32 = [4][3]int32{
		{10, 20, 30},
		{50, 60, 70},
		{80, 90, 100},
		{110, 120, 130},
	}

	var s1 [][3]int32 = ma[:]       // expected

	var s2 [][3]int32 = ma[:][:]	// ????

	var s3 [][]int32 = ma[0:2][0:2]	// ????
}

var s1 [][3]int32 = ma[:] behaves as expected. ma[:] creates a slice of [3]int32 arrays, so we have an underlaying array with each element of type [3]int32 array. Tottally expected behaviour for me.

Problems arise when defining s1 and s2. It's not behaving as I expected. var s2 [][3]int32 = ma[:][:] gives the same result as var s1 [][3]int32 = ma[:]. I expected it to make a slice of slices, not a slice of arrays. How is it possible? How can the two give the same result?

Additionally, I expect var s3 [][]int32 = ma[0:2][0:2] to create a slice of slices as well. Instead it gives the error "cannot use ma[0:2][0:2] (value of type [][3]int32) as [][]int32 value in variable declaration compiler". So somehow, with ma[0:2][0:2] it gives the type [][3]int32, not [][]int32. How?

I hope I have explained what is not clear to me.

答案1

得分: 2

表达式ma[:][:]解析为(ma[:])[:]。该表达式在ma的切片表达式的结果上进行切片表达式的求值。外部切片表达式是一个空操作。

Go语言没有多维切片表达式。

英文:

The expression ma[:][:] parses as (ma[:])[:]. The expression evaluates to a slice expression on the result of the slice expression on ma. The outer slice expression is a noop.

Go does not have multidimensional slice expressions.

huangapple
  • 本文由 发表于 2022年11月15日 00:58:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/74435233.html
匿名

发表评论

匿名网友

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

确定