开发者

Getting a reflect.Type from a name

If I have a name of a type (i.e "container/vector"), i开发者_高级运维s there a way to lookup the reflect.Type that has the given name? I'm trying to write a simple database-backed workqueue system and this it would be very difficult without this feature.


I can't see how this would be possible in any trivial way (or at all), since name resolution is part of the compiler/linker, not the runtime.

However, http://github.com/nsf/gocode might offer up some ideas. Though I'm pretty sure that works by processing the .a files in $GOROOT, so I still don't see how you'd get the reflect.Type. Maybe if the exp/eval package was more mature?

Of course if you know all the possible types you'll encounter, you could always make a map of the reflect.Type. But I'm assuming you're working with unpredictable input, or you would've thought of that.


Only way to create a reflect.Type is by having a concrete value of the intended type first. You can't even create composite-types, such as a slice ([]T), from a base type (T).

The only way to go from a string to a reflect.Type is by entering the mapping yourself.

mapping := map[string]reflect.Type {
  "string": reflect.Typeof(""),
  "container/vector": reflect.Typeof(new(vector.Vector)),
  /* ... */
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜