go - Instance new Type (Golang) -


can tell me how create new instance of type string? reflect?

there examples older (pre go 1 versions) of language [:(]

so, if understand question correctly, asking how can create object when have name of type string. so, example, might have string "mystruct" , want create object of type.

unfortunately, that's not possible because go statically typed language , linker eliminate dead code (or inline parts of it). so, there no guarantee, final executable contain code of "mystruct".

you can however, maintain global map[string]reflect.type manually. example initializing map in init() function of packages defines such discover-able types. tell compiler using types. afterwards, can use map reflect.type of type want create , use reflect.new pointer new object of type (stored reflect.value). can extract object interface this:

reflect.new(yourtype).elem().interface() 

elem() de-reference pointer , interface() return reflected value interface{}. see the laws of reflection further details.

ps: there might better way structure program doesn't require reflection , let compiler catch more errors. have considered using factory method example? other easy solution might maintain map[string]func() interface{} of functions can invoked create new object name.


Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

python - build a suggestions list using fuzzywuzzy -