2 回答
TA贡献1824条经验 获得超6个赞
使用以下代码递归映射、数组和任何类型的切片:
func walk(v reflect.Value) {
fmt.Printf("Visiting %v\n", v)
// Indirect through pointers and interfaces
for v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface {
v = v.Elem()
}
switch v.Kind() {
case reflect.Array, reflect.Slice:
for i := 0; i < v.Len(); i++ {
walk(v.Index(i))
}
case reflect.Map:
for _, k := range v.MapKeys() {
walk(v.MapIndex(k))
}
default:
// handle other types
}
}
TA贡献1856条经验 获得超17个赞
以下是为我工作
func main() {
x := MapType{
"a": MapType{
"x": MapType{
"p": ArrayType{"l", "o", "l"},
},
} ,
}
d := &Document{}
fmt.Println(d.throughMap(x))
}
type Document struct {}
type MapType map[string]interface{}
type ArrayType []interface{}
func (doc *Document) throughMap(docMap MapType) MapType {
for k, v := range docMap {
fmt.Println(k, v)
vt := reflect.TypeOf(v)
switch vt.Kind() {
case reflect.Map:
if mv, ok := v.(MapType); ok {
docMap[k] = doc.throughMap(mv)
} else {
panic("error.")
}
case reflect.Array, reflect.Slice:
if mv, ok := v.(ArrayType); ok {
docMap[k] = doc.throughArray(mv)
} else {
panic("error.")
}
default:
docMap[k] = doc.processType(v)
}
}
return docMap
}
func (doc *Document) throughArray(arrayType ArrayType) ArrayType {
return arrayType
}
func (doc *Document) processType(x interface{}) interface{} {
return x
}
- 2 回答
- 0 关注
- 129 浏览
添加回答
举报