蛋蛋星球 后台端
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

slice_and_string.go 1.3 KiB

пре 1 месец
пре 3 недеља
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. }