示例来源:// source multidimensional slicevar source = []interface{}{ "value1", "value2", 1234, 1234.1234, []int{222, 333}, []float32{444.444, 555.555}, []interface{}{555, "value4", []int{777, 888}}}目标:// target []stringvar target = []string{ "value1", "value2", "1234", "1234.1234", "222", "333", "444.444", "555.555", "555", "value4", "777", "888"}我写了转换函数。但这在我看来很麻烦,并且没有涵盖所有可能的选择。你能告诉我可以有更优雅的决定吗?
1 回答
慕标5832272
TA贡献1966条经验 获得超4个赞
使用 reflect 包在几行代码中处理所有类型的切片:
func convert(dst []string, v reflect.Value) []string {
// Drill down to the concrete value
for v.Kind() == reflect.Interface {
v = v.Elem()
}
if v.Kind() == reflect.Slice {
// Convert each element of the slice.
for i := 0; i < v.Len(); i++ {
dst = convert(dst, v.Index(i))
}
} else {
// Convert value to string and append to result.
dst = append(dst, fmt.Sprint(v.Interface()))
}
return dst
}
像这样称呼它:
stringSlice := convert(nil, reflect.ValueOf(source))
- 1 回答
- 0 关注
- 82 浏览
添加回答
举报
0/150
提交
取消