Getting from a string to an object value - how?


(Vinay Sajip) #1

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.


(Sean Killian) #2

Hi, Vinay, it’s not possible to access objects (I mean functions, types, variables) by just its name in Go. Go by design omits code and data that it can prove is unreachable. Being able to access functions, variables or types from just their names would break the go tool’s ability to track where they’re used.

A “workaround” is if you know the set of options, you can build-up a lookup in your code, e.g.:

var names = map[string]interface{} {
    "os": map[string]interface{} {
        "Stdin": os.Stdin,
    }
}

// GetName gets an object by its name. It doesn't loop correctly,
// but you get the idea!
func GetName(name string) (interface{}, bool) {
    m := names
    var v interface{}
    for _, part := range strings.Split(name, ".") {
        var ok bool
        v, ok = m[part]
        if !ok {
            return nil, false
        }
        m, ok = v.(map[string]interface{})
        if ok {
            continue
        }
    }
    return v, true
}

I don’t recommend doing this, though.


(Vinay Sajip) #3

OK, thanks for the response! It’s a shame this can’t be done - unfortunately, this is in relation to a general-purpose configuration library, where developers can specify things in the configuration that they would have in their own programs. The library could have no knowledge of what those things are, so the lookup approach isn’t usable. Oh, well.