在Golang中初始化具有不同大小的数组数组。

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

Initialize array of arrays with different sizes in Golang

问题

在Golang中,我想初始化一个数组的数组,用来表示一年的数据。
主数组将有12个子数组,每个子数组代表一个月。每个子数组的大小将根据它们代表的月份而定。

例如,第0个子数组将代表一月,并包含31个元素;第1个子数组将代表二月,并包含29个元素(考虑闰年),依此类推。

在Golang中,多维数组可以使用[12][30]int这样的方式进行初始化,但在这里,我需要使用不同大小的多维数组。我该如何初始化这样一种数据类型的变量呢?

简而言之,我想做的事情类似于这样:

var year = [12][31]int{{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}}

但是我在语法上遇到了困难。有人可以帮我解决吗?谢谢!

英文:

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!!

答案1

得分: 2

你想要这样的代码吗?

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]))
	}
}

在 Go Playground 上运行:链接

英文:

You want something like this?

package main

import &quot;fmt&quot;

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

run in go playground

答案2

得分: 2

稍微更一致的答案参考@Sakib。我假设你也想填写日期。

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])
}
英文:

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 &lt; 12; i++ {
	months[i] = make([]int, days[i])
	for j := 0; j &lt; days[i]; j++ {
		months[i][j] = j + 1
	}
	fmt.Println(i+1, months[i])
}

答案3

得分: 1

如果你想要初始化一个表示年份的二维数组,其中多维数组的初始化方式类似于 [12][30]int,我认为以下代码可以解决你的问题:

package main

import (
	"errors"
	"fmt"
	"log"
	"strconv"
	"time"
)

func main() {
	years := []int{
		2022,
		1972,
		2021,
		2020,
	}

	var s string
	for _, year := range years {
		s = ""
		ret, err := GetYearDays(year)
		if err != nil {
			log.Fatal(err)
		}
		for i := range ret {
			s = s + " " + strconv.Itoa(len(ret[i]))
		}
		log.Printf("year: %d, month days:%s\n", year, s)
	}
}

func GetYearDays(year int) (ret [12][]int, err error) {
	// year check depends on the user
	if year < 1952 || year > 3000 {
		return ret, errors.New("invalid year")
	}

	for idx := range ret {
		firstDay, err := time.Parse("2006-1-2", fmt.Sprintf("%d-%d-1", year, idx+1))
		if err != nil {
			return ret, fmt.Errorf("time invalid, year: %d, month: %d", year, idx+1)
		}
		lastDay := firstDay.AddDate(0, 1, -1)
		ret[idx] = make([]int, lastDay.Day())
	}
	return ret, err
}

希望对你有帮助!

英文:

if you want to initialize an array of arrays which can represent an year and multi-dimensional arrays are initialized like [12][30]int, I think this code may solve your problem:

package main

import (
	&quot;errors&quot;
	&quot;fmt&quot;
	&quot;log&quot;
	&quot;strconv&quot;
	&quot;time&quot;
)

func main() {
	years := []int{
		2022,
		1972,
		2021,
		2020,
	}

	var s string
	for _, year := range years {
		s = &quot;&quot;
		ret, err := GetYearDays(year)
		if err != nil {
			log.Fatal(err)
		}
		for i := range ret {
			s = s + &quot; &quot; + strconv.Itoa(len(ret[i]))
		}
		log.Printf(&quot;year: %d, month days:%s\n&quot;, year, s)
	}
}

func GetYearDays(year int) (ret [12][]int, err error) {
	// year check depends on the user
	if year &lt; 1952 || year &gt; 3000 {
		return ret, errors.New(&quot;invalid year&quot;)
	}

	for idx := range ret {
		firstDay, err := time.Parse(&quot;2006-1-2&quot;, fmt.Sprintf(&quot;%d-%d-1&quot;, year, idx+1))
		if err != nil {
			return ret, fmt.Errorf(&quot;time invalid, year: %d, month: %d&quot;, year, idx+1)
		}
		lastDay := firstDay.AddDate(0, 1, -1)
		ret[idx] = make([]int, lastDay.Day())
	}
	return ret, err
}

huangapple
  • 本文由 发表于 2022年8月14日 18:01:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/73350712.html
匿名

发表评论

匿名网友

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

确定