英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论