util.go 687 B

12345678910111213141516171819202122232425262728293031323334
  1. package model
  2. import (
  3. "fmt"
  4. "reflect"
  5. "strings"
  6. )
  7. // Implode function like php
  8. func Implode(list interface{}, seq string) string {
  9. listValue := reflect.Indirect(reflect.ValueOf(list))
  10. if listValue.Kind() != reflect.Slice {
  11. return ""
  12. }
  13. count := listValue.Len()
  14. listStr := make([]string, 0, count)
  15. for i := 0; i < count; i++ {
  16. v := listValue.Index(i)
  17. if str, err := getValue(v); err == nil {
  18. listStr = append(listStr, str)
  19. }
  20. }
  21. return strings.Join(listStr, seq)
  22. }
  23. func getValue(value reflect.Value) (res string, err error) {
  24. switch value.Kind() {
  25. case reflect.Ptr:
  26. res, err = getValue(value.Elem())
  27. default:
  28. res = fmt.Sprint(value.Interface())
  29. }
  30. return
  31. }