duanbodai5166 2019-07-24 09:34
浏览 37
已采纳

编写函数以从映射中获取字符串键的片段,而不管映射是什么值类型

I want to write a function to get all keys from a map as a slice of string which key type is string and the value could be any other type.

Like this but can have any kind of map[string]... as input.

func mapLowCaseKeys(v map[string]string) []string {
    keys := make([]string, len(v))
    i := 0
    for key := range v {
        keys[i] = strings.ToLower(key)
        i++
    }
    return keys
}

Actually I want achive Object.keys() in Javascript.

I've tried use map[string]interface{} as the function's paramter type but it can't just pass any specific map to that function, is this possible in golang?

  • 写回答

1条回答 默认 最新

  • douweng7308 2019-07-24 10:26
    关注

    You can make use MapKeys in reflect package to do that(ref: https://golang.org/pkg/reflect/#Value.MapKeys).

    MapKeys returns a slice containing all the keys present in the map, in unspecified order. It panics if v's Kind is not Map. It returns an empty slice if v represents a nil map.

    An example is given below (playground link: https://play.golang.org/p/xhDtmbGUyz0):

    package main
    
    import (
        "fmt"
        "reflect"
    )
    
    func main() {
        fmt.Println(mapLowCaseKeys(map[string]float64{
            "key1" : 1.2,
        }))
    
        fmt.Println(mapLowCaseKeys(map[string]interface{} {
            "key1" : 1.2,
            "key2" : map[string]string{"kk": "3"},
        }))
    
        fmt.Println(mapLowCaseKeys(map[int]float64{
             11 : 1.2,
        }))
    
        fmt.Println(mapLowCaseKeys(nil))
    }
    
    func mapLowCaseKeys(v interface{}) []string {
        keys := []string{}
        value := reflect.ValueOf(v)
        if value.Kind() == reflect.Map {
            for _, v := range value.MapKeys() {
                if v.Kind() == reflect.String {
                    keys = append(keys, v.String())
                }
            }
            return keys
        } else {
            fmt.Println("it is not a map!!")
            return keys
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题
  • ¥15 github训练的模型参数无法下载
  • ¥15 51单片机显示器问题
  • ¥20 关于#qt#的问题:Qt代码的移植问题
  • ¥50 求图像处理的matlab方案
  • ¥50 winform中使用edge的Kiosk模式
  • ¥15 关于#python#的问题:功能监听网页
  • ¥15 怎么让wx群机器人发送音乐
  • ¥15 fesafe材料库问题