如何在Golang中定义数组的切片长度?

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

how to define length of slices into array in golang?

问题

我有一个切片数组,我想定义切片的长度,因为当我尝试运行代码时出现了恐慌:

panic: runtime error: index out of range [0] with length 0

代码如下:

func Transpose(m [][]int) [][]int{
    arr := make([][]int, len(m))

    for i:=0; i < len(arr); i++ {
        for j:=0; j<len(arr); j++ {
            arr[j][i] = m[i][j]
        }
    }

return arr
}
英文:

I have an array of slices and I want to define length of slices, because when I'm trying to launch a code getting the panic:

panic: runtime error: index out of range [0] with length 0

the code:

func Transpose(m [][]int) [][]int{
	arr := make([][]int, len(m))

	for i:=0; i &lt;len(arr); i++ {
		for j:=0; j&lt;len(arr); j++ {
			arr[j][i] = m[i][j]
		}
	}
	
return arr
}

答案1

得分: 3

问题在于您没有初始化每个内部切片。arr := make([][]int, len(m))只初始化了arr切片的外部循环。

func Transpose(m [][]int) [][]int {
	arr := make([][]int, len(m))

	for i := 0; i < len(m); i++ {

		arr[i] = make([]int, len(m[i]))

		for j := 0; j < len(m[i]); j++ {
			arr[i][j] = m[j][i]
		}
	}

	return arr
}
英文:

The issue is that you haven't initialised each inner slice. arr := make([][]int, len(m)) only initialise the outer loop of the arr slice.

func Transpose(m [][]int) [][]int {
	arr := make([][]int, len(m))

	for i := 0; i &lt; len(m); i++ {

		arr[i] = make([]int, len(m[i]))

		for j := 0; j &lt; len(m[i]); j++ {
			arr[i][j] = m[j][i]
		}
	}

	return arr
}

huangapple
  • 本文由 发表于 2023年6月24日 13:00:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76544626.html
匿名

发表评论

匿名网友

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

确定