dsomm80482 2016-06-09 13:50
浏览 798
已采纳

在go中用逗号分割字符串后,获得[]接口{}

I have two ways to get a list.

  1. via api - which returns me a map[string]interface{}. The value I am interested in is stored in interface as []interface{} (array of strings which are by default set to array of interface)
  2. via static string - if api fails. This is a comma separated string. I use the strings.Split function which results in an []string

The above results in data of two types []interface{} and []string which is not compatible for the operations an I will have to perform same operation separately based on the type.

Further I am converting the array to a map[string]int with key as string and value as 1. I am converting it to a map for quick checking of some attributes in the original array

Is there any solution to the problem and what is the best way to do it..

  • 写回答

1条回答 默认 最新

  • doulei8861 2016-06-09 13:53
    关注

    Use the following code to create a map[string]int from comma separated values in a string s:

    m := make(map[string]int)
    for _, p := range strings.Split(s, ",") {
       m[p] = 1
    }
    

    Use the following code to create a map[string]int from values of type []interface{}:

    m := make(map[string]int)
    for _, v := range values {
       s, ok := v.(string)
       if !ok {
          // not a string, handle error
       }
       m[s] = 1
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器