I'm trying to add 2 items at once to a struct array, then continuously every 2 items create a new struct array and append to the final Container
struct. I'm struggling to find the proper way of doing this.
To further illustrate what I mean:
package main
import "fmt"
type Container struct {
Collection []SubContainer
}
type SubContainer struct {
Key string
Value int
}
func main() {
commits := map[string]int{
"a": 1,
"b": 2,
"c": 3,
"d": 4,
"e": 5,
"f": 6,
}
sc := []SubContainer{}
c := Container{}
for k, v := range commits {
sc = append(sc, SubContainer{Key: k, Value: v})
}
for _, s := range sc {
c.Collection = append(c.Collection, s)
}
fmt.Println(c)
}
Link: https://play.golang.org/p/OhSntFT7Hp
My desired behaviour is to loop through all the commits
, and every time the SubContainer
reaches len(2), append to the Container
, and create a new SubContainer
until the for loop is complete. If there's an uneven number of elements, then the last SubContainer would just hold one element and append to Container like normal.
Does anyone have any suggestions on how to do this? Apologies if this is a obvious answer, very new to Go!