1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 |
- package util
- import (
- "errors"
- "reflect"
- )
- // 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
- }
- func ContainsElement(slice interface{}, element interface{}) (bool, error) {
- sliceValue := reflect.ValueOf(slice)
- if sliceValue.Kind() != reflect.Slice {
- return false, errors.New("没有输入切片。")
- }
- for i := 0; i < sliceValue.Len(); i++ {
- currentElement := sliceValue.Index(i).Interface()
- if reflect.DeepEqual(currentElement, element) {
- return true, nil
- }
- }
- return false, nil
- }
|