I need a big table of structs and I need to work off the struct returned.
package main
import (
"fmt"
)
var factory map[string]interface{} = map[string]interface{}{
"Date": Date{},
"DateTime": DateTime{},
}
type Date struct {
year int //xsd:int Year (e.g., 2009)
month int //xsd:int Month (1..12)
day int //xsd:int Day number
}
func( d *Date ) Init(){
d.year = 2009
d.month = 1
d.day = 1
}
type DateTime struct {
date Date //Date
hour int //xsd:int
minute int //xsd:int
second int //xsd:int
timeZoneID string //xsd:string
}
func( d *DateTime ) Init(){
d.hour = 0
d.minute = 0
d.second = 0
}
func main() {
obj := factory["Date"]
obj.Init()
fmt.Println( obj )
}
Go Playground but I get the error obj.Init undefined (type interface {} is interface with no methods) Is there a way to do this?
Basically, you need to tell the compiler that all your types (instances in the map) will always have an Init method. For that you declare an interface with the Init method and build a map of that interface. Since your receivers work on a pointer *xxx, you need to add the pointers of the objects to the map (not the objects themselves) by adding & in front of them.
package main
import (
"fmt"
)
type initializer interface {
Init()
}
var factory map[string]initializer = map[string]initializer{
"Date": &Date{},
"DateTime": &DateTime{},
}
type Date struct {
year int //xsd:int Year (e.g., 2009)
month int //xsd:int Month (1..12)
day int //xsd:int Day number
}
func (d *Date) Init() {
d.year = 2009
d.month = 1
d.day = 1
}
type DateTime struct {
date Date //Date
hour int //xsd:int
minute int //xsd:int
second int //xsd:int
timeZoneID string //xsd:string
}
func (d *DateTime) Init() {
d.hour = 0
d.minute = 0
d.second = 0
}
func main() {
obj := factory["Date"]
obj.Init()
fmt.Println(obj)
}