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.

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

报告相同问题?

悬赏问题

  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 MATLAB四叉树处理长方形tif文件
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 使用Java milo连接Kepserver服务端报错?
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?
  • ¥20 软件开发方法学习来了