可以将值映射为可变类型吗?

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

Can map values be variable types?

问题

在Golang中,map中的值可以是类型吗?例如,我如何创建一个类似于以下形式的map:m[string]type,

 m["abc"] = int
 m["def"] = string
 m["ghi"] = structtype(某个structtype类型的结构体)

我需要这样的map,因为我有一个函数,它有一个字符串参数,根据该字符串参数,函数会创建一个特定类型的变量并执行一些操作。因此,如果我有一个将字符串映射到类型的map,函数可以使用字符串参数作为键来检查该map,以找出它需要创建哪种类型的变量。

英文:

In Golang, the values in map, can they be types ? For example how do I create a map m[string]type such that it can be like this,

 m["abc"] = int
 m["def"] = string
 m["ghi"] = structtype ( some structure of type structtype)

I need such map because, I have a function which has a string argument and according to that string argument the function creates a variable of a certain type and does some operations. So, if I have a map which maps a string to a type, the function can check that map using the string argument as the key to find out which type of variable it needs to create.

答案1

得分: 4

看起来你需要使用map[string]reflect.Type

val := map[string]reflect.Type{}

val["int"] = reflect.TypeOf(int(0))
pointer_to_new_item := reflect.New(val["int"])

如果你需要一个非指针值,你可以使用Indirect

new_item := reflect.Indirect(pointer_to_new_item)

使用reflect创建一个值会得到一个reflect.Value,你需要使用其他reflect函数从中提取出你想要的实际值。更多信息请参阅reflect文档

请注意,reflect.New只能创建简单类型、结构体等。如果你需要通道、映射或切片,还有其他类似的函数可以像make内置函数一样使用。

英文:

I sounds like you need map[string]reflect.Type

val := map[string]reflect.Type{}{}

val["int"] = reflect.TypeOf(int(0))
pointer_to_new_item := reflect.New(val["int"])

If you need a non-pointer value you then use Indirect:

new_item := reflect.Indirect(pointer_to_new_item)

Using reflect to create a value will give you a reflect.Value, which you then need to unpack the actual value you want from using other reflect functions. See The reflect documentation for more info.

Keep in mind that reflect.New only makes simple types, structures, etc. If you need channels, maps, or slices there are other, similar functions that work like the make builtin.

huangapple
  • 本文由 发表于 2017年7月28日 04:37:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/45360582.html
匿名

发表评论

匿名网友

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

确定