亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將多維切片[]接口{}轉換為切片[]字符串?

如何將多維切片[]接口{}轉換為切片[]字符串?

Go
交互式愛情 2023-06-01 17:57:55
示例來源:// 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))

在操場上運行


查看完整回答
反對 回復 2023-06-01
  • 1 回答
  • 0 關注
  • 111 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號