蛋蛋星球 后台端
 
 
 
 

67 lines
1.3 KiB

  1. package utils
  2. import (
  3. "fmt"
  4. "reflect"
  5. "strings"
  6. "unsafe"
  7. )
  8. // string与slice互转,零copy省内存
  9. // zero copy to change slice to string
  10. func Slice2String(b []byte) (s string) {
  11. pBytes := (*reflect.SliceHeader)(unsafe.Pointer(&b))
  12. pString := (*reflect.StringHeader)(unsafe.Pointer(&s))
  13. pString.Data = pBytes.Data
  14. pString.Len = pBytes.Len
  15. return
  16. }
  17. // no copy to change string to slice
  18. func StringToSlice(s string) (b []byte) {
  19. pBytes := (*reflect.SliceHeader)(unsafe.Pointer(&b))
  20. pString := (*reflect.StringHeader)(unsafe.Pointer(&s))
  21. pBytes.Data = pString.Data
  22. pBytes.Len = pString.Len
  23. pBytes.Cap = pString.Len
  24. return
  25. }
  26. // 任意slice合并
  27. func SliceJoin(sep string, elems ...interface{}) string {
  28. l := len(elems)
  29. if l == 0 {
  30. return ""
  31. }
  32. if l == 1 {
  33. s := fmt.Sprint(elems[0])
  34. sLen := len(s) - 1
  35. if s[0] == '[' && s[sLen] == ']' {
  36. return strings.Replace(s[1:sLen], " ", sep, -1)
  37. }
  38. return s
  39. }
  40. sep = strings.Replace(fmt.Sprint(elems), " ", sep, -1)
  41. return sep[1 : len(sep)-1]
  42. }
  43. func DiffArray(a []string, b []string) []string {
  44. var diffArray []string
  45. temp := map[string]struct{}{}
  46. for _, val := range b {
  47. if _, ok := temp[val]; !ok {
  48. temp[val] = struct{}{}
  49. }
  50. }
  51. for _, val := range a {
  52. if _, ok := temp[val]; !ok {
  53. diffArray = append(diffArray, val)
  54. }
  55. }
  56. return diffArray
  57. }