How I can get instance of struct by it name

2,979 views
Skip to first unread message

kil...@gmail.com

unread,
Oct 19, 2013, 4:17:49 PM10/19/13
to golan...@googlegroups.com
I have struct MyStruct

type MyStruct struct {
    Name string 
}

How I can get instance of MyStruct and using string like struct name?

For example:

func getInstance(instanceName string) interface{} {
    // some happened here and I have instance of MyStruct
-----
I know, I can create global array like:
someArray map[string] reflect.Type
But, How I can get instance of MyStruct by string (it Name) without that?

Sorry, if that stupid question.

Matt Harden

unread,
Oct 19, 2013, 5:39:14 PM10/19/13
to kil...@gmail.com, golang-nuts
The Go compiler does not retain the names of types in the compiled code, so there is no way for reflection to get at that information.


--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

egon

unread,
Oct 19, 2013, 5:42:30 PM10/19/13
to golan...@googlegroups.com, kil...@gmail.com
I don't think you can do that, you need to register the structs somewhere. e.g. http://play.golang.org/p/igmssSD9k2. If they were always included the linker wouldn't be able to remove unnecessary code.

You could also automatically generate that file, if that registration is too much maintenance.

+ egon

kilatiB Shtikhno

unread,
Oct 19, 2013, 7:07:06 PM10/19/13
to egon, golan...@googlegroups.com
I think that way useful for me. How I can automatically generate that file and AppEngine allow automatically that file?? 

egon

unread,
Oct 19, 2013, 8:03:31 PM10/19/13
to golan...@googlegroups.com, egon, kil...@gmail.com
The generation is a separate build step, so you probably need to do that before uploading to AppEngine. Although there may be some support for custom building. You can use the "go/ast" and "go/parser" to write something that walks over your code and generates the file (http://golang.org/src/pkg/go/ast/example_test.go).

Manually registering in pacakge init() will be probably easier (e.g. func init(){ my_struct_package.Register(MyStruct{}) } ).  I don't know which one is suitable for you, but the init method should work quite nicely for most cases. If you need to separate the struct registry from the struct definition then just write the array of to register the structs. If this becomes too time consuming, then it's probably worth the effort for writing automatic generation.

I would probably go with creating a separate file that registers all the structs, and, only if needed, create the "automatic struct registration" generator.

+ egon
Reply all
Reply to author
Forward
0 new messages