Home > Backend Development > Golang > How to define length of slice as array in golang?

How to define length of slice as array in golang?

WBOY
Release: 2024-02-08 21:45:24
forward
395 people have browsed it

How to define length of slice as array in golang?

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!

Question content

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
Copy after login

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
}
Copy after login

Workaround

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
}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template