【原创】golang []interface多维取值

小豆丁 1年前 ⋅ 195 阅读

 

多维切片想要取值,这里我写了一份,主函数和使用方法如下:


//SliceGetValue []interface{}多维取值,只取第一次找到的值
func SliceGetValue(data []interface{}, depth int, indexes []int) (interface{}, []int, error) {
	if depth <= 0 {
		return data, indexes, nil
	}

    depth--

	for k, r := range data {
		if row, ok := r.([]interface{}); ok {
			indexes = append(indexes, k)
			if depth > 0 {
				//继续找下一级
				return SliceGetValue(row, depth, indexes)
			} else {
				//查找结束
				return row, indexes, nil
			}
		}
	}

	return nil, indexes, errors.New("no key slice")
}

//标例
func main() {
	d := []interface{}{
		"a",
		"a1",
		[]interface{}{
			"b",
			"b1",
			"b2",
			[]interface{}{
				[]interface{}{
					"d",
					1,
				},
				"c",
			},
		},
	}

	s, indexes, err := SliceGetValue(d, 3, []int{})
	fmt.Println(s)
	fmt.Println(indexes)
	fmt.Println(err)
}

 

要调用的函数,循环搜索并回调结果:

//SliceSearchCallback 切片循环搜索回调
func SliceSearchCallback(data []interface{}, depth int, indexes []int, f func(row []interface{}, depth int, indexes []int)) []int {
	if depth <= 0 {
		return indexes
	}

	depth--

	for k, r := range data {
		if row, ok := r.([]interface{}); ok {
			indexes = append(indexes, k)
			if depth > 0 {
				//继续找下一级
				indexes = SliceSearchCallback(row, depth, indexes, f)
			} else {
				//查找结束执行回调函数
				f(row, depth, indexes)
				indexes = make([]int, 0)
			}
		}
	}

	return indexes
}

func main() {
	//new(DocxParser).Parse("aa.txt")
	d := []interface{}{
		"a",
		"a1",
		[]interface{}{
			"b",
			"b1",
			"b2",
			[]interface{}{
				[]interface{}{
					"d",
					1,
				},
				"c",
			},
		},
		[]interface{}{
			"ab",
			"ab1",
			"ab2",
			[]interface{}{
				[]interface{}{
					"ad",
					11,
				},
				"ac",
			},
		},
	}

	SliceSearchCallback(d, 1, []int{}, func(r []interface{}, depth int, indexes []int) {
		fmt.Println(r)
		fmt.Println(depth)
		fmt.Println(indexes)
	})
}

全部评论: 0

    我有话说: