I'm trying to play around with recursive structs, where when I have multiple I can add them together, creating a new struct with those embedded. However, I'm not sure what the proper way to approach this is.
I've included a code snippet below to further illustrate what I mean.
package main
import "fmt"
type Container struct {
F int
Collection []SubContainer
}
type SubContainer struct {
Key string
Value int
}
func main() {
commits := map[string]int{
"a": 1,
"b": 2,
"c": 3,
"d": 4,
}
sc := []SubContainer{}
c := []Container{}
count := 0
for k, v := range commits {
sc = append(sc, SubContainer{Key: k, Value: v})
count++
if len(sc) == 2 {
c = append(c, Container{Collection: sc, F: count})
sc = nil
}
}
for _, r := range c {
fmt.Println(r)
}
}
Result:
{2 [{a 1} {b 2}]}
{4 [{c 3} {d 4}]}
Desired result:
{6 {2 [{a 1} {b 2}]} {4 [{c 3} {d 4}]}}
Playground link: https://play.golang.org/p/j6rbhgcOoT
One caveat I'm having trouble wrapping my head around is that the commits
length may change (I was initially thinking I could just create a different parent struct). Any suggestions would be appreciated... Is doing this somehow with recursive structs the right approach to accomplish this? Thanks!