u_slice.go 711 B

12345678910111213141516171819202122232425262728
  1. package util
  2. // AppendIfNotExists 向切片中追加元素,如果元素已存在则不添加
  3. func AppendIfNotExists(slice []string, element string) []string {
  4. for _, item := range slice {
  5. if item == element {
  6. return slice // 元素已存在,直接返回原切片
  7. }
  8. }
  9. return append(slice, element) // 元素不存在,追加到切片末尾
  10. }
  11. func MergeSlice(slice1 []string, slice2 []string) []string {
  12. // 遍历第二个切片中的元素,并去重追加到结果切片1中
  13. for _, element := range slice2 {
  14. found := false
  15. for _, item := range slice1 {
  16. if element == item {
  17. found = true
  18. break
  19. }
  20. }
  21. if !found {
  22. slice1 = append(slice1, element)
  23. }
  24. }
  25. return slice1
  26. }