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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?