Golang dynamic instantiation of a struct

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.


Truth Http://stackoverflow.com/questions/10210188/instance-new-type-golang

So, if I understand your question correctly, you is asking about what you can create a object when you just has the name of the type as String. So, for example, you might has a string "MyStruct" and you want to create an object of the this type.

Unfortunately, that's not easily possible because Go is a Statically typed language and the linker would eliminate dead code (or inline parts of it). So, there was no guarantee, that your final executable would even contain the code of "MyStruct".

you can however, maintain a global map[string]reflect. Type  manually. For example by initializing this map in The init ()  function of your packages which defines such discover-able types . This would also tell the compiler and that is using the types. Afterwards, you can use this map to look up the reflect. Type of the type you want to create and use reflect. New to get a pointer to a new object of the that type (stored as a reflect. Value). You can extract the object to an interface with something like this:

reflect.New(Yourtype).Elem().Interface()

elem ()  will de-reference the Pointer and interface ()  will return the reflected Value as An interface{} . See the Laws of Reflection for further details.

Ps:there might be a better-structure your program which doesn ' t even require reflection and which let the compiler Catch more errors. Has the considered using a factory method for example? An and easy solution might is to maintain a of map[string]func() interface{} functions which can is invoked to create a new object with the that Nam E.




http://mikespook.com/2012/07/%E5%9C%A8-golang-%E4%B8%AD%E7%94%A8%E5%90%8D%E5%AD%97%E8%B0%83%E7%94%A8%E5%87%BD%E6%95%B0/

But here's a limitation: This map can only be used as a function of "func ()" Without input parameters or return values.
If you want to use this method to implement functions that call different function prototypes, you need to use interface{}.


Reference *****************


1. Https://www.socketloop.com/tutorials/golang-fix-type-interface-has-no-field-or-no-methods-and-type-assertions-example

Golang:fix type interface{} has no field or no methods and type assertions example



2. Golang instantiate a struct with a string reflection

Package main import ("FMT" "reflect") type Foo struct {}type Bar struct {}//To save the instantiated struct object var regstruct map[string]interf ace{} func Main () {str: = "Bar" if REGSTRUCT[STR]! = nil {  T: = reflect. ValueOf (Regstruct[str]). Type ()  V: = reflect. New (t). Elem ()  FMT. Println (v)}} func init () {regstruct = make (map[string]interface{}) regstruct["Foo"] = foo{} regstruct["Bar"] = bar{}}



3. http://stackoverflow.com/questions/17507697/dry-out-my-go-function-with-interfaces


kinds:=Map[string]func() Entity {    "User":func() Entity { return &User{} },    "Space":func() Entity { return &Space{} },    " the Hostel":func() Entity { return & the{} },}  funcCreate(Kindstring) {instance:=kinds[Kind]()Decoder.Decode(instance)saveentity(instance)}

4. Novice Solver golang dynamic new struct

Http://www.oschina.net/question/1388294_141504?sort=default&p=2#answers

<span style= "FONT-SIZE:14PX;" > I'm doing this now var modelobj map[string]interface{} = map[string]interface{}{"Member": New (Member),} func getmodobj (mod String) interface{} {if modelobj[mod]! = nil {return Modelobj[mod]} else {return nil}} </span>


5. Http://stackoverflow.com/questions/13856539/how-do-you-get-struct-value-on-unknown-interface



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.