slice.go 768 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package buildin
  2. // InSlice 判断自字符串是否在另一个字符串内
  3. func InSlice[T comparable](item T, slice []T) bool {
  4. for _, s := range slice {
  5. if s == item {
  6. return true
  7. }
  8. }
  9. return false
  10. }
  11. // Intersection 求交集
  12. func Intersection[T comparable](a, b []T) []T {
  13. var res []T
  14. if len(a) == 0 || len(b) == 0 {
  15. return res
  16. }
  17. m := make(map[T]bool)
  18. for _, v := range a {
  19. m[v] = true
  20. }
  21. for _, v := range b {
  22. if m[v] {
  23. res = append(res, v)
  24. }
  25. }
  26. return res
  27. }
  28. // RemoveDuplicates 去除重复值
  29. func RemoveDuplicates[T comparable](slice []T) []T {
  30. unique := make(map[T]bool)
  31. result := make([]T, 0, len(slice))
  32. for _, s := range slice {
  33. if !unique[s] {
  34. unique[s] = true
  35. result = append(result, s)
  36. }
  37. }
  38. return result
  39. }