Yes, what you did reports if the key type is "exactly" string
.
But for example if the key type would be a custom type having string
as its underlying type, like in this example:
type mystr string
m := map[mystr]int{}
Then the key type would not be equal to reflect.TypeOf("")
.
It's up to you if this is what you want. If you do want to accept the above map types too, you may check the kind of the key if it equals to reflect.String
like this:
if v.Type().Key() == reflect.TypeOf("") {
fmt.Print("It is string")
}
if v.Type().Key().Kind() == reflect.String {
fmt.Print("It is string kind")
}
For the above map[mystr]int
, this is the output (try it on the Go Playground):
It is string kind
(The key is not of type string
, but it is of kind string
.)