Create Struct from string

2,576 views
Skip to first unread message

Jeremy Villalobos

unread,
Apr 19, 2012, 7:46:32 PM4/19/12
to golan...@googlegroups.com
I want to send a Struct across a network.  I understand the use of gob, but gob requires the name of the struct, and my use case requires the remote node to 
receive the data, and create the structure based on the received data.  So I can send a packet <struct name, struct data >

From this code, I can get the name of the struct.  

type myStruct struct {
  One int
  Two float64
}
p := reflect.ValueOf( &f )
name := p.Type().String()
fmt.Println( name )

Is there a way to get the struct instantiated from the string:

p := reflect.New( name ) //and p being type myStruct 

I'll dive into the implementation of the rpc module to figure it out myself, but in the meantime I appreciate discussing it.

Hotei

unread,
Apr 19, 2012, 9:52:49 PM4/19/12
to golan...@googlegroups.com
Generic solution is to create a string or []byte that contains an XML style definition of your struct, send the XML over the network and then on the receiver side parse it back into an appropriate struct.  That is pretty much what JSON does so you might want to look there.  Is there a special reason you need to re-invent this?

Jeremy Villalobos

unread,
Apr 19, 2012, 10:10:04 PM4/19/12
to Hotei, golan...@googlegroups.com
It is not about sending the structure from one computer to the other.  It is about instantiating the structure on the remote node without knowing the type of the structure.  I am probably not explaining myself well.  Let me speak in Java.

public class Bar {

}
Bar aBar;
String barClassName = "com.mypackage.Bar";
aBar = (Bar) Class.forName(barClassName).newInstance();

Thanks for the reply
Message has been deleted

Kyle Lemons

unread,
Apr 20, 2012, 12:14:14 PM4/20/12
to Peter Thrun, golan...@googlegroups.com, Hotei
You can actually cheat better than that by sending interfaces :)

http://play.golang.org/p/hDCVPuxGF6

On Thu, Apr 19, 2012 at 7:26 PM, Peter Thrun <peter...@ymail.com> wrote:
aBar = (Bar) Class.forName(barClassName).newInstance();

Go does not have a a function like this, but you can build something similar in your application.

var factories = map[string]func()interface{}{
   "mypackage.Bar": func() { return &mypackage.Bar{} },
   ... more types here
}

aBar = factories["mypackage.Bar"]().(*mypackage.Bar)



Reply all
Reply to author
Forward
0 new messages