Would the following be considered idiomatic Go code?
My main concerns are:
The use of maps for this purpose. I basically want the data structure to be completely dynamic in size and have easy access to elements by id. This is because I will want to retrieve specific items on demand lots of times, so I don't want to loop each time.
The check for the map element
My use of pointers
General flow and structure
package main
import (
"fmt"
)
type BoxItem struct {
Id int
Qty int
}
func NewBox() *Box {
return &Box{make(map[int]*BoxItem), 0}
}
type Box struct {
BoxItems map[int]*BoxItem
}
func (this *Box) AddBoxItem(id int, qty int) *Box {
i, ok := this.BoxItems[id]
if ok {
i.Qty += qty
} else {
boxItem := &BoxItem{id, qty}
this.BoxItems[id] = boxItem
}
return this
}
func main() {
box := NewBox()
box.AddBoxItem(1, 1)
fmt.Printf("There are %d items in the box", len(box.BoxItems))
}