In Golang, slices and arrays are two different data types. A slice is a dynamic length sequence, while an array is a fixed length sequence. If you want to define the length of a slice as an array, you can do so by creating a fixed-length array and then using the slice to reference that array. The specific operation is to first create an array of specified length, and then use a slice to reference part of the elements of the array, so that the length of the slice can be defined as the length of the array. This approach can simulate the behavior of an array to a certain extent, while also taking advantage of the flexibility of slicing. Hope this short answer helps you!
I have an array of slices and I want to define the length of the slices because when I try to start the code I get a panic:
panic: runtime error: index out of range [0] with length 0
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 }
The problem is that you haven't initialized each inner slice. arr := make([][]int, len(m))
Only initializes the arr
outer loop of the 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 }
The above is the detailed content of How to define length of slice as array in golang?. For more information, please follow other related articles on the PHP Chinese website!