patterngoMinor
Box data structure in Go
Viewed 0 times
boxstructuredata
Problem
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
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))
}Solution
Instead of
a more idiomatic usage is
Calling the receiver
You seem to want to make your method chainable. I'm not sure this is a frequent practice in Go but it's probably more a matter of style and experience than a question of idiomatic code or not.
The rest could be condensed a little but that's not a matter of idiom. I have nothing to say regarding your use of pointers.
i, ok := this.BoxItems[id]
if ok {
i.Qty += qty
}a more idiomatic usage is
if i, ok := this.BoxItems[id]; ok {
i.Qty += qty
}Calling the receiver
this doesn't seem like a good practice to me. Calling it box would be clearer.You seem to want to make your method chainable. I'm not sure this is a frequent practice in Go but it's probably more a matter of style and experience than a question of idiomatic code or not.
The rest could be condensed a little but that's not a matter of idiom. I have nothing to say regarding your use of pointers.
Code Snippets
i, ok := this.BoxItems[id]
if ok {
i.Qty += qty
}if i, ok := this.BoxItems[id]; ok {
i.Qty += qty
}Context
StackExchange Code Review Q#29524, answer score: 4
Revisions (0)
No revisions yet.