optimization - In golang, how can you get a reflect.Type instance of an struct without physically creating the struct? -
i want create registry of struct types enable dynamic loading of solutions 'project euler' problems. current solution requires struct first created , zeroed before it's type can registered:
package solution import ( "errors" "fmt" "os" "reflect" ) type solution interface { load() solve() string } type solutionregister map[string]reflect.type func (sr solutionregister) set(t reflect.type) { fmt.printf("registering %s\n", t.name()) sr[t.name()] = t } func (sr solutionregister) get(name string) (solution, error) { if typ, ok := sr[name]; ok { sol := reflect.new(typ).interface().(solution) return sol, nil } return nil, errors.new("invalid solution: " + name) } var solutionsregistry = make(solutionregister) func register(sol solution) { solutionsregistry.set(reflect.typeof(sol).elem()) } func load(s string) solution { sol, err := solutionsregistry.get(s) if err != nil { fmt.printf("error loading solution %s (%s)\n", s, err) os.exit(-1) } sol.load() return sol } type dummysolution struct { data [100 * 1024 * 1024 * 1024]uint8 } func (s *dummysolution) load() { } func (s *dummysolution) solve() string { return "" } func init() { register(&dummysolution{}) }
in example type of 'dummysolution struct' registered inside init() function. structure purposefully absurdly large illustrate problem.
is there way access type of dummysolution , other solutions without having create instance of structure beforehand?
you can use reflect.typeof((*dummysolution)(nil)).elem()
. making nil
pointer doesn't allocate space whole struct, , elem
(described under definition of reflect.type
) gets pointer (or slice, array, channel, or map) element type.
Comments
Post a Comment