猿问

如何将多维切片[]接口{}转换为切片[]字符串?

示例来源:


// source multidimensional slice

var source = []interface{}{

    "value1",

    "value2",

    1234,

    1234.1234,

    []int{222, 333},

    []float32{444.444, 555.555},

    []interface{}{555, "value4", []int{777, 888}}

}

目标:


// target []string

var target = []string{

    "value1",

    "value2",

    "1234",

    "1234.1234",

    "222",

    "333",

    "444.444",

    "555.555",

    "555",

    "value4",

    "777",

    "888"

}

我写了转换函数。但这在我看来很麻烦,并且没有涵盖所有可能的选择。你能告诉我可以有更优雅的决定吗?


交互式爱情
浏览 83回答 1
1回答

慕标5832272

使用 reflect 包在几行代码中处理所有类型的切片:func convert(dst []string, v reflect.Value) []string {&nbsp; &nbsp; // Drill down to the concrete value&nbsp; &nbsp; for v.Kind() == reflect.Interface {&nbsp; &nbsp; &nbsp; &nbsp; v = v.Elem()&nbsp; &nbsp; }&nbsp; &nbsp; if v.Kind() == reflect.Slice {&nbsp; &nbsp; &nbsp; &nbsp; // Convert each element of the slice.&nbsp; &nbsp; &nbsp; &nbsp; for i := 0; i < v.Len(); i++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dst = convert(dst, v.Index(i))&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; // Convert value to string and append to result.&nbsp; &nbsp; &nbsp; &nbsp; dst = append(dst, fmt.Sprint(v.Interface()))&nbsp; &nbsp; }&nbsp; &nbsp; return dst}像这样称呼它:stringSlice := convert(nil, reflect.ValueOf(source))在操场上运行
随时随地看视频慕课网APP

相关分类

Go
我要回答