func TestStructGetAllFieldMap(ot *testing.T) { t1 := reflect.TypeOf(&GetAllFieldT1{}) ret := kmgReflect.StructGetAllFieldMap(t1) kmgTest.Equal(ret["A"].Index, []int{0, 0}) kmgTest.Equal(ret["B"].Index, []int{2}) kmgTest.Equal(ret["C"].Index, []int{0, 2, 2}) kmgTest.Equal(ret["D"].Index, []int{1, 1}) kmgTest.Equal(len(ret), 7) ret = kmgReflect.StructGetAllFieldMap(reflect.TypeOf(&GetAllFieldT5{})) kmgTest.Equal(ret["A"].Index, []int{1}) kmgTest.Equal(len(ret), 2) }
//假设map的key类型是string,值类型不限 func StructToMap(t Transformer, in reflect.Value, out reflect.Value) (err error) { oValType := out.Type().Elem() oKey := reflect.New(reflect.TypeOf("")).Elem() if out.IsNil() { out.Set(reflect.MakeMap(out.Type())) //新建map不能使用reflect.New } fieldMap := kmgReflect.StructGetAllFieldMap(in.Type()) for key, field := range fieldMap { if field.PkgPath != "" { //忽略没有导出的字段 continue } iVal := in.FieldByName(key) oVal := reflect.New(oValType).Elem() err = t.Tran(iVal, oVal) if err != nil { return } oKey.SetString(key) out.SetMapIndex(oKey, oVal) } return nil }