I'm trying to understand how to manipulate data structures in Go, and its approach to pointers (with copies or references).
my code is on Go Playground, here: https://play.golang.org/p/j_06RS5Xcz
I made up a map of slices of a struct that also has a slice of other thing inside.
here:
type Item struct {
Name string
Description string
}
type Entity struct {
Base Item
Others []Item
}
var database map[int][]Entity
func main() {
database = make(map[int][]Entity)
database[1] = []Entity{}
e1 := Entity{}
e1.Base = Item{"A", "aaa"}
e1.Others = []Item{}
database[1] = append(database[1], e1)
// later, I want to add other items to my entity
e1.Others = append(e1.Others, Item{"B", "bbb"})
// other items field is empty
fmt.Println(database)
}
// prints: map[1:[{{A aaa} []}]]
I want to append the Others items later in my program. it seems that I must use pointers to solve this, but I don't know how.
should my Entity be like this?
type Entity struct {
Base Item
Others *[]Item
}
and if so, how should I append items to it? like this?
*e1.Others = append(*e1.Others, Item{"B", "bbb"})
.
.
.
if there is room for another question... it is also not clear to me if I 'must' do: database[1] = []Entity{}
before database[1] = append(database[1], e1)
or I could just append in this case. I tried the same on e1.Others = []Item{}
but it didn't produced the same effect to append (I know that this is my misunderstanding, not a Go's fault).
thanks in advance :)