github.com/jtzjtz/kit@v1.0.2/array/array.go (about) 1 package array 2 3 import ( 4 "errors" 5 "reflect" 6 ) 7 8 //判断数组或切片中是否存在某元素 9 func Contains(find interface{}, target interface{}) (bool, error) { 10 targetValue := reflect.ValueOf(target) 11 switch reflect.TypeOf(target).Kind() { 12 case reflect.Slice, reflect.Array: 13 for i := 0; i < targetValue.Len(); i++ { 14 if targetValue.Index(i).Interface() == find { 15 return true, nil 16 } 17 } 18 case reflect.Map: 19 if targetValue.MapIndex(reflect.ValueOf(find)).IsValid() { 20 return true, nil 21 } 22 } 23 24 return false, errors.New("not in array") 25 } 26 func In_Array(val interface{}, array interface{}) bool { 27 exists := false 28 switch reflect.TypeOf(array).Kind() { 29 case reflect.Slice: 30 s := reflect.ValueOf(array) 31 for i := 0; i < s.Len(); i++ { 32 if reflect.DeepEqual(val, s.Index(i).Interface()) == true { 33 exists = true 34 } 35 } 36 } 37 return exists 38 } 39 40 //求数组的并集、交集、差集----int-array 41 //求并集 42 func UnionArray(slice1, slice2 []int32) []int32 { 43 m := make(map[int32]int) 44 for _, v := range slice1 { 45 m[v]++ 46 } 47 for _, v := range slice2 { 48 times, _ := m[v] 49 if times == 0 { 50 slice1 = append(slice1, v) 51 } 52 } 53 return slice1 54 } 55 56 //求交集 57 func IntersectArray(slice1, slice2 []int32) []int32 { 58 m := make(map[int32]int) 59 nn := make([]int32, 0) 60 for _, v := range slice1 { 61 m[v]++ 62 } 63 64 for _, v := range slice2 { 65 times, _ := m[v] 66 if times == 1 { 67 nn = append(nn, v) 68 } 69 } 70 return nn 71 } 72 73 //求差集 (slice1去掉slice2中存在的元素) 74 func DifferenceArray(slice1, slice2 []int32) []int32 { 75 m := make(map[int32]int) 76 nn := make([]int32, 0) 77 inter := IntersectArray(slice1, slice2) 78 for _, v := range inter { 79 m[v]++ 80 } 81 82 for _, value := range slice1 { 83 times, _ := m[value] 84 if times == 0 { 85 nn = append(nn, value) 86 } 87 } 88 return nn 89 }