通用地图值 [英] generic map value
问题描述
当我想以类似的方式使用地图键时,我遇到了几次这个问题,但是地图中的值是不同的.我以为我可以编写一个函数,将我想要的键类型与interface {}用作值类型,但是它不起作用.
I have run into this problem a few times when wanting to use keys of maps in a similar way but the values in the maps are different. I thought I could write a function that takes the key type I want with interface{} as the value type but it doesn't work.
func main() {
mapOne := map[string]int
mapTwo := map[string]double
mapThree := map[string]SomeStruct
useKeys(mapOne)
}
func useKeys(m map[string]interface{}) {
//something with keys here
}
不确定是否有一种优雅的方法可以做到这一点,我只是觉得腰部饱满地将简单的东西重写为不同的值.
Not sure if there is an elegant way to do this I just feel waist full rewriting simple things for different values.
推荐答案
尽管go中的映射和切片本身是通用的,但它们不是协变的(它们也不是协变的,因为接口不是通用的).这是使用没有泛型的语言的一部分,您将不得不重复一些事情.
Though maps and slices in go are generic themselves, they are not covariant (nor could they be, since interfaces aren't generics). It's part of working with a language that doesn't have generics, you will have to repeat some things.
如果您真的只需要获取任何旧地图的键,则可以使用反射来做到这一点:
If you really just need to get the keys of any old map, you can use reflection to do so:
func useKeys(m interface{}) {
v := reflect.ValueOf(m)
if v.Kind() != reflect.Map {
fmt.Println("not a map!")
return
}
keys := v.MapKeys()
fmt.Println(keys)
}
这篇关于通用地图值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!