Getting from a string to an object value - how?

95 views
Skip to first unread message

Vinay Sajip

unread,
Jan 14, 2020, 1:28:01 PM1/14/20
to golang-nuts
I have a string value that I’d like to convert into an actual object in my running program. The string would be read from a configuration file. For example, the string "os:Stdin" should be processable somehow to get the actual variable os.Stdin. Is that possible in Go? The reflect package seems to only work on objects you already have; I’ve also had a look at the go/importer package, but that seems to primarily deal with source-level information and doesn’t seem to allow you to bridge from there to already existing objects in memory. Other-language equivalents would be Class.forName(...) in Java or Assembly.GetType(...) in C#. Can anyone supply any useful pointers? I know about the plugin package, but AFAIK it doesn’t work on Windows.

Regards,

Vinay Sajip

Ian Lance Taylor

unread,
Jan 14, 2020, 4:58:01 PM1/14/20
to Vinay Sajip, golang-nuts
On Tue, Jan 14, 2020 at 10:27 AM 'Vinay Sajip' via golang-nuts
<golan...@googlegroups.com> wrote:
>
> I have a string value that I’d like to convert into an actual object in my running program. The string would be read from a configuration file. For example, the string "os:Stdin" should be processable somehow to get the actual variable os.Stdin. Is that possible in Go? The reflect package seems to only work on objects you already have; I’ve also had a look at the go/importer package, but that seems to primarily deal with source-level information and doesn’t seem to allow you to bridge from there to already existing objects in memory. Other-language equivalents would be Class.forName(...) in Java or Assembly.GetType(...) in C#. Can anyone supply any useful pointers? I know about the plugin package, but AFAIK it doesn’t work on Windows.

In general this is not possible in Go. Sorry.

If you can restrict yourself to exported package-scope variables, then
you can probably use the debug/pe (on Windows) package to look up the
symbol name and use that value as the variable's address.

Or in some cases you can keep a registry of names that you need to find.

Note that by default the Go linker will discard unreferenced variables
and functions, so the fact that a variable exists in the package
doesn't mean it will exist in the final linked executable.

Ian

Vinay Sajip

unread,
Jan 15, 2020, 4:53:59 AM1/15/20
to golang-nuts


On Tuesday, 14 January 2020 21:58:01 UTC, Ian Lance Taylor wrote:
In general this is not possible in Go.  Sorry.

If you can restrict yourself to exported package-scope variables, then
you can probably use the debug/pe (on Windows) package to look up the
symbol name and use that value as the variable's address.

Or in some cases you can keep a registry of names that you need to find.

OK, thanks for the response.

Regards,

Vinay Sajip
Reply all
Reply to author
Forward
0 new messages