This is a creation in Article, where the information may have evolved or changed.
Impolde method is commonly used in PHP string stitching method, in Golang also has the function of string concatenation:
strings.Join(a []string, sep string) string
This function is similar to implode, but has one drawback: the first argument must be []string, and if you want to stitch []int into a string, you need to convert.
The following uses reflection to implement a common "implode" approach:
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}
Then make a simple test:
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)}
Output:
1,2,3,4,5,6,71,2,3,4,5,6,71.5,2.1,3,4,5.9,6.7,7.7res: str,19,19.999,true
is not convenient many:)