英文:
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 <len(arr); i++ {
for j:=0; j<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 < 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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论