如何在不知道键/值类型的情况下测试一个interface{}是否是一个map?

huangapple go评论92阅读模式
英文:

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
}

huangapple
  • 本文由 发表于 2013年6月10日 18:06:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/17021356.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定