递归切片

package main

import (
    "encoding/json"
    "log"
    "reflect"
)

func main() {
    reversePrint([]interface{}{"1", 2, "a", []string{"haha", "88"}, 1.1})
}

// 不使用for循环逆序输出数组,数组中可存放数组类型或值类型,遇值类型直接输出,遇数组类型拆解开到外层逆输输出.
// 如[]interface{}{"1", 2, "a", []string{"haha", "88"}, 1.1} 输出:1.1,"88","haha","a",2,"1"
func reversePrint(xs []interface{}) {
    if len(xs) == 0 {
        return
    }
    reversePrint(xs[1:])
    v := xs[0]
    t := reflect.TypeOf(v)
    switch t.Kind() {
    case reflect.Slice:
        vi := reflect.ValueOf(v)
        vd := make([]interface{}, vi.Len())
        for i := 0; i < vi.Len(); i++ {
            vd[i] = vi.Index(i)
        }
        reversePrint(vd)
    default:
        log.Println(v)
    }
}

你可能感兴趣的:(递归切片)