dqssst0144 2015-11-20 16:48
浏览 34
已采纳

如何获取地图的所有键和值并将其作为args传递给golang中的函数?

I encountered such a situation:

Got a map first, and its size is unknown.

E.g.: myMap map[string]string

And then, I would take all the keys and values of the map as a function's args

e.g func(key1, key2, ..., value1, value2, ...)

An example func: https://godoc.org/github.com/garyburd/redigo/redis#Script.Do

How to achieve this in go?

As efficient as impossible.

Any help will be appreciated :)

  • 写回答

2条回答 默认 最新

  • dongluo3331 2015-11-20 17:03
    关注

    We can query the length of the map with the builtin len() function. So we can create a big-enough slice to hold all the keys and all the values.

    After that it's enough to iterate over the map only once, and you can fill the first half of the slice with the keys, and the second half of the slice with the values.

    This is as efficient as it can get: no builtin append() is called, and we iterate over the map only once.

    Let's see an example function that will receive the keys and values. This one just prints all of them:

    func pairs(keysvalues ...string) {
        for _, s := range keysvalues {
            fmt.Print(s, ", ")
        }
    }
    

    And the code that creates the keysvalues slice:

    m := map[string]string{
        "a": "A",
        "b": "B",
        "c": "C",
    }
    
    count := len(m)
    all := make([]string, count*2)
    
    i := 0
    for k, v := range m {
        all[i], all[count+i] = k, v
        i++
    }
    

    Once you have the all slice, you can call the pairs() function like this:

    pairs(all...)
    

    Note though that the iteration order over a map is not deterministic, it may change from iteration to iteration.

    Example output (try it on the Go Playground):

    a, b, c, A, B, C, 
    

    Note:

    In your question you indicated that all keys come first and then follow all the values:

    func(key1, key2, ..., value1, value2, ...)
    

    In practice this is rare and often the key-value pairs are listed. It's much easier to work/process this variant:

    func pairs(key1, value1, key2, value2, ... keyn, valuen)
    

    If we would want to produce this key-value pair list, very similarly it would look like this:

    count := len(m)
    all := make([]string, count*2)
    
    i := 0
    for k, v := range m {
        all[i], all[i+1] = k, v
        i += 2
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?