Home > OS >  Initialize array of arrays with different sizes in Golang
Initialize array of arrays with different sizes in Golang

Time:08-15

In Golang, I want to initialize an array of arrays which can represent an year. The main array will have 12 sub-arrays each will represent a month. Each subarray will have size of the month they represent.

For eg, 0th sub-array will reference January and will contain 31 elements, 1st sub-array will reference February and will contain 29 elements (considering a leap year) and so on...

Multi-dimensional arrays are initialized like [12][30]int in Golang considering the fixed size. But here, I am working with a multidimensional array of different sizes. How do I initialize a variable with such a datatype?

In short, I want to do something like this:

var year [[31]int, [29]int, [31]int, [30]int, [31]int, [30]int, [31]int, [31]int, [30]int, [31]int, [30]int, [31]int]

But I am struggling with the syntax. Could someone please help me out? Thanks!!

CodePudding user response:

You want something like this?

package main

import "fmt"

func main() {
    days := []int{31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
    months := [12][]int{}
    for i := 0; i < 12; i   {
        months[i] = make([]int, days[i])
        fmt.Println(i, months[i], len(months[i]))
    }
}

run in go playground

CodePudding user response:

A slightly more consistent answer reference @Sakib. And I assumed you wanted the dates to be filled too.

days := []int{31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
months := make([][]int, len(days))
for i := 0; i < 12; i   {
    months[i] = make([]int, days[i])
    for j := 0; j < days[i]; j   {
        months[i][j] = j   1
    }
    fmt.Println(i 1, months[i])
}
  • Related