go実装implodeメソッド

1780 ワード

impoldeメソッドはphpでよく使われる文字列接合メソッドで、golangにも文字列接合の関数があります.
strings.Join(a []string, sep string) string

この関数はimplodeと似ていますが、1つ目のパラメータは[]stringでなければなりません.[]intを文字列につなぐには変換が必要です.次に、反射を使用して、一般的な「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

便利かどうかはたくさんあります:)