doufeiqiong3515 2017-07-27 20:37
浏览 34
已采纳

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

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条回答 默认 最新

  • duai4512 2017-07-27 20:45
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?