我有一个足够通用的函数来遍历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]string
或map[string][]string
go不会将每个值复制到新类型。您可以采用最通用的interface{}
类型,然后进行转换。
关于function - 获取不同内容 map 的所有 map 键[字符串],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64137894/