function - 获取不同内容 map 的所有 map 键[字符串]

标签 function dictionary go

我有一个足够通用的函数来遍历map [string]并获取所有键:

i := 0
keys := make([]string, len(input))
for k := range input {
    keys[i] = k
    i++
}
return keys
我的问题是我想在这里输入两个不同的输入: map [string] MyStruct map [string] [] [] float64 。每当我尝试将功能输入作为map [string] interface {}时,go都会拒绝尝试将map [string] MyStruct强制转换为map [string] interface {}的所有尝试。有没有一种方法,我不需要两个功能,一个以map [string] MyStruct作为输入,一个以map [string] [] [] float64为函数?此时map [string]的内容无关紧要,因为我只是想获取它们的所有键,以便稍后在代码中使用。这需要一个被调用的函数。我们正在使用Sonar,并且它设置为拒绝代码重复,因此我无法重复此代码段。

最佳答案

在下一个Go版本为我们带来泛型之前,有几种方法可以解决它。

  • 重复的代码
  • 使用代码生成-设计一些模板,然后继续构建将为您填充它。
  • 使用interface{}作为函数的输入类型,然后使用反射来猜测为函数指定的类型。
    我很确定在这种情况下,通用代码会比2个单独的函数更复杂。
  • func getKeys(input interface{}) []string {
        switch inp := input.(type) {
        case map[string]MyStruct:
            keys := make([]string, 0, len(inp))
            for k := range inp {
                keys = append(keys, k)
            }
            return keys
        case map[string][]float64:
            ...
        default:
            fmt.Printf("I don't know about type %T!\n", v)
    }
    
    您不能使用输入类型map[string]interface{}放置map[string]stringmap[string][]string go不会将每个值复制到新类型。您可以采用最通用的interface{}类型,然后进行转换。

    关于function - 获取不同内容 map 的所有 map 键[字符串],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64137894/

    相关文章:

    c++ - 将结构添加到映射中

    go - 如何在 golang 中更新一个 bigquery 行

    arrays - 为什么当通过 ParamArray 将数组元素传递给函数时,函数中会到达 varpointer?

    swift - Switft Dictionary 问题 'String?' is not convertible to 'String' ;您的意思是使用 'as!' 强制向下转换吗?

    python - 鉴于文本之间有很多空格,如何将文本行拆分为多行?

    python - 为 JSON 格式化 Python 字典

    validation - Golang 验证器无效的内存地址或 nil 指针取消引用

    arrays - 获取嵌套数组中具有特定ObjectId的数组对象

    javascript - D3 Javascript - 嵌套函数可能存在问题 - 生成控制台错误

    python - 在Python中以不同的步骤转移数据