12345678910111213141516171819202122232425262728 |
- package util
- // AppendIfNotExists 向切片中追加元素,如果元素已存在则不添加
- func AppendIfNotExists(slice []string, element string) []string {
- for _, item := range slice {
- if item == element {
- return slice // 元素已存在,直接返回原切片
- }
- }
- return append(slice, element) // 元素不存在,追加到切片末尾
- }
- func MergeSlice(slice1 []string, slice2 []string) []string {
- // 遍历第二个切片中的元素,并去重追加到结果切片1中
- for _, element := range slice2 {
- found := false
- for _, item := range slice1 {
- if element == item {
- found = true
- break
- }
- }
- if !found {
- slice1 = append(slice1, element)
- }
- }
- return slice1
- }
|