go 實現(xiàn) implode 方法

impolde 方法是 php 中常用的字符串拼接方法, 在golang 中也有字符串拼接的函數(shù):

strings.Join(a []string, sep string) string

此函數(shù)與implode類似, 但有個缺點: 第一個參數(shù)必須是 []string, 如果想將[]int 拼接為字符串就需要轉(zhuǎn)換.
下面利用反射實現(xiàn)一個通用的"implode"方法:

func Implode(list interface{}, seq string) string {
    listValue := reflect.Indirect(reflect.ValueOf(list))
    if listValue.Kind() != reflect.Slice {
        return ""
    }
    count := listValue.Len()
    listStr := make([]string, 0, count)
    for i := 0; i < count; i++ {
        v := listValue.Index(i)
        if str, err := getValue(v); err == nil {
            listStr = append(listStr, str)
        }
    }
    return strings.Join(listStr, seq)
}


func getValue(value reflect.Value) (res string, err error) {
    switch value.Kind() {
    case reflect.Ptr:
        res, err = GetValue(value.Elem())
    default:
        res = fmt.Sprint(value.Interface())
    }
    return
}

然后簡單做個測試:

func TestImplode(t *testing.T) {
    list := []int{1, 2, 3, 4, 5, 6, 7}
    res := Implode(list, ",")
    fmt.Println(res)

    list1 := []int16{1, 2, 3, 4, 5, 6, 7}
    res = Implode(list1, ",")
    fmt.Println(res)


    list2 := []float64{1.5, 2.1, 3.0, 4, 5.9, 6.7, 7.7}
    res = Implode(list2, ",")
    fmt.Println(res)


    var list3  []float64
    res = Implode(list3, ",")
    fmt.Println("res: ", res)

    list4 := make([]interface{}, 4, 4)
    list4[0] = "str"
    list4[1] = 19
    list4[2] = 19.999
    list4[3] = true
    res = Implode(list4, ",")
    fmt.Println(res)

}

輸出:

1,2,3,4,5,6,7
1,2,3,4,5,6,7
1.5,2.1,3,4,5.9,6.7,7.7
res:  
str,19,19.999,true

是不是方便很多 :)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容