general value of the card

I encountered this problem several times when I wanted to use the card keys in the same way, but the values ​​on the cards are different. I thought I could write a function that uses the key type that I want with the {} interface as a value type, but it does not 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 that the waist completely rewrites simple things for different values.

+7
source share
1 answer

Although maps and fragments in go themselves are generic, they are not covariant (and cannot be, since interfaces are not generics). This is part of working with a language that does not have generics; you will have to repeat some things.

If you really need to get the keys of any old card, you can use reflection for this:

 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) } 
+12
source

Source: https://habr.com/ru/post/1202268/


All Articles