广告平台(站长下代理使用)
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 1021 B

3 months ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. }