gpt4 book ai didi

dictionary - 映射值可以是变量类型吗?

转载 作者:IT王子 更新时间:2023-10-29 02:29:11 24 4
gpt4 key购买 nike

在Golang中,map中的值,可以是类型吗?例如,我如何创建一个 m[string]type 的 map ,使其像这样,

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

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

最佳答案

我听起来你需要 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.Value,然后你需要使用其他反射函数解压你想要的实际值。参见 The reflect documentation了解更多信息。

请记住,reflect.New 只制作简单的类型、结构等。如果您需要 channel 、映射或 slice ,还有其他类似的功能,与 make 内置。

关于dictionary - 映射值可以是变量类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45360582/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com