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 如何构建全国统一的物流管理平台?
  • ¥100 ijkplayer使用AndroidStudio/CMake编译,如何支持 rtsp 直播流?
  • ¥20 和学习数据的传参方式,选择正确的传参方式有关
  • ¥15 这是网络安全里面的poem code
  • ¥15 用js遍历数据并对非空元素添加css样式
  • ¥15 使用autodl云训练,希望有直接运行的代码(关键词-数据集)
  • ¥50 python写segy数据出错
  • ¥20 关于线性结构的问题:希望能从头到尾完整地帮我改一下,困扰我很久了
  • ¥30 3D多模态医疗数据集-视觉问答
  • ¥20 设计一个二极管稳压值检测电路