u_slice.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package util
  2. import (
  3. "errors"
  4. "reflect"
  5. )
  6. // AppendIfNotExists 向切片中追加元素,如果元素已存在则不添加
  7. func AppendIfNotExists(slice []string, element string) []string {
  8. for _, item := range slice {
  9. if item == element {
  10. return slice // 元素已存在,直接返回原切片
  11. }
  12. }
  13. return append(slice, element) // 元素不存在,追加到切片末尾
  14. }
  15. func MergeSlice(slice1 []string, slice2 []string) []string {
  16. // 遍历第二个切片中的元素,并去重追加到结果切片1中
  17. for _, element := range slice2 {
  18. found := false
  19. for _, item := range slice1 {
  20. if element == item {
  21. found = true
  22. break
  23. }
  24. }
  25. if !found {
  26. slice1 = append(slice1, element)
  27. }
  28. }
  29. return slice1
  30. }
  31. func ContainsElement(slice interface{}, element interface{}) (bool, error) {
  32. sliceValue := reflect.ValueOf(slice)
  33. if sliceValue.Kind() != reflect.Slice {
  34. return false, errors.New("没有输入切片。")
  35. }
  36. for i := 0; i < sliceValue.Len(); i++ {
  37. currentElement := sliceValue.Index(i).Interface()
  38. if reflect.DeepEqual(currentElement, element) {
  39. return true, nil
  40. }
  41. }
  42. return false, nil
  43. }