I have a number of structs that share some common properties and logic, but I haven't been able to find a way to share logic that works. Basically, I have a file as part of a package that handles "widgets". I wanted to have a general Widget struct that's embedded in each specified widget struct WidgetA and WidgetB, then share a bit of logic during the creation process. For example:
type Widget struct {
name string
}
type WidgetA struct {
Widget
inspector string
}
type WidgetB struct {
Widget
length int
height int
}
func (w *Widget) Init() {
// Do some shared things
// Then figure out which _type_ of Widget this is and delegate
// to the appropriate receiver function
}
func (wa *WidgetA) Create () { ... }
func (wb *WidgetB) Create () { ... }
On the calling end, maybe something like this:
widgetA := &WidgetA{}
widgetA.Init()
I can't find a working solution to share the logic in Go, so I'd like to either understand where I'm going wrong or, if I'm going wrong be trying to apply old habits where they don't belong, figure out the most idiomatic way of accomplishing the same goal using Go.
Insight appreciated!