从名称获取反射类型

huangapple go评论88阅读模式
英文:

Getting a reflect.Type from a name

问题

如果我有一个类型的名称(例如"container/vector"),是否有一种方法可以查找具有给定名称的reflect.Type?我正在尝试编写一个简单的基于数据库的工作队列系统,如果没有这个功能,将会非常困难。

英文:

If I have a name of a type (i.e "container/vector"), is 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.

答案1

得分: 1

我无法看到以任何简单的方式(或根本不可能)实现这一点,因为名称解析是编译器/链接器的一部分,而不是运行时。

然而,http://github.com/nsf/gocode 可能会提供一些想法。虽然我相当确定它是通过处理$GOROOT中的.a文件来工作的,所以我仍然不明白你如何获得reflect.Type。也许如果exp/eval包更成熟一些会有办法?

当然,如果你知道所有可能遇到的类型,你可以始终创建一个reflect.Type的映射。但我假设你正在处理不可预测的输入,否则你早就想到了这一点。

英文:

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.

答案2

得分: 0

只有通过首先拥有预期类型的具体值,才能创建reflect.Type。甚至无法从基本类型(T)创建复合类型,例如切片([]T)。

stringreflect.Type的唯一方法是手动输入映射。

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

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)),
  /* ... */
}

huangapple
  • 本文由 发表于 2010年8月26日 00:59:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/3568418.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定