impolde 方法是 php 中常用的字符串拼接方法, 在golang 中也有字符串拼接的函数:
strings.Join(a []string, sep string) string
此函数与implode类似, 但有个缺点: 第一个参数必须是 []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
是不是方便很多 :)
有疑问加站长微信联系(非本文作者)