如果地图值可以是任何类型,则使用反射来遍历地图:
if v.Kind() == reflect.Map { for _, key := range v.MapKeys() { strct := v.MapIndex(key) fmt.Println(key.Interface(), strct.Interface()) }}游乐场的例子
如果存在少量已知的结构类型,则可以使用类型开关:
func process(in interface{}) { switch v := in.(type) { case map[string]*Book: for s, b := range v { // b has type *Book fmt.Printf("%s: book=%vn" s, b) } case map[string]*Author: for s, a := range v { // a has type *Author fmt.Printf("%s: author=%vn" s, a) } case []*Book: for i, b := range v { fmt.Printf("%d: book=%vn" i, b) } case []*Author: for i, a := range v { fmt.Printf("%d: author=%vn" i, a) } case *Book: fmt.Ptintf("book=%vn", v) case *Author: fmt.Printf("author=%vn", v) default: // handle unknown type }}


