Is this idiomatic go code - dealiing with maps
Would the following be considered idiomatic go code. I think the concerns
are over the use of pointers and the checking for map element exists: i,
ok
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))
}
No comments:
Post a Comment