英文:
How to test whether an interface{} is a map without knowing key/value types?
问题
尽管可以测试一个interface{}
是否是已知键/值类型的映射:
func TypeTest(thing interface{}) {
switch thing.(type) {
case map[string]string:
fmt.Println("map string string")
case map[string]interface{}:
fmt.Println("map string")
case map[interface{}]interface{}:
fmt.Println("map")
case interface{}:
fmt.Println("interface")
default:
fmt.Println("unknown")
}
}
TypeTest(map[string]string{"a": "1"}) // "map string string"
TypeTest(map[string]int{"a": 1}) // "interface" !!!
但是,如果我只想知道一个interface{}
是否是映射,而不用担心它的键/值类型,该怎么办?
英文:
Although it is possible to test whether an interface{}
is a map of known key/value type:
func TypeTest(thing interface{}) {
switch thing.(type) {
case map[string]string:
fmt.Println("map string string")
case map[string]interface{}:
fmt.Println("map string")
case map[interface{}]interface{}:
fmt.Println("map")
case interface{}:
fmt.Println("interface")
default:
fmt.Println("unknown")
}
}
TypeTest(map[string]string{"a": "1"}) // "map string string"
TypeTest(map[string]int{"a": 1}) // "interface" !!!
But what if I just want to know whether an interface{}
is a map or not, without worrying about its key/value type?
答案1
得分: 9
你可以使用reflect
包来实现这个功能。
package main
import "fmt"
import "reflect"
func main() {
m := make(map[string]int)
fmt.Printf("%v\n", isMap(m))
}
func isMap(m interface{}) bool {
rt := reflect.TypeOf(m)
return rt.Kind() == reflect.Map
}
英文:
You can use the reflect
package for this.
package main
import "fmt"
import "reflect"
func main() {
m := make(map[string]int)
fmt.Printf("%v\n", isMap(m))
}
func isMap(m interface{}) bool {
rt := reflect.TypeOf(m)
return rt.Kind() == reflect.Map
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论