示例來源:// 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 關注
- 111 瀏覽
添加回答
舉報
0/150
提交
取消