From 4f8a7b43df73a62ac5e49b17650fb76c6da94a65 Mon Sep 17 00:00:00 2001 From: yangzm <18675616014@163.com> Date: Mon, 6 Dec 2021 20:38:02 +0800 Subject: [PATCH] =?UTF-8?q?=E3=80=90=E6=9D=A8=E3=80=91=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E5=88=87=E7=89=87=E5=8E=BB=E9=87=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- slice.go | 32 ++++++++++++++++++++++++++++++++ slice_test.go | 6 ++++++ 2 files changed, 38 insertions(+) diff --git a/slice.go b/slice.go index 6627ebb..97d3bf8 100644 --- a/slice.go +++ b/slice.go @@ -3,6 +3,11 @@ */ package helper +import ( + "errors" + "fmt" +) + // 求差集 func Diff(slice1, slice2 []string) []string { m := make(map[string]int) @@ -52,5 +57,32 @@ func Union(slice1, slice2 []string) []string { } } return slice1 +} +func Unique(originals interface{}) (interface{}, error) { + temp := map[string]struct{}{} + switch slice := originals.(type) { + case []string: + result := make([]string, 0, len(originals.([]string))) + for _, item := range slice { + key := fmt.Sprint(item) + if _, ok := temp[key]; !ok { + temp[key] = struct{}{} + result = append(result, item) + } + } + return result, nil + case []int64: + result := make([]int64, 0, len(originals.([]int64))) + for _, item := range slice { + key := fmt.Sprint(item) + if _, ok := temp[key]; !ok { + temp[key] = struct{}{} + result = append(result, item) + } + } + return result, nil + default: + return nil, errors.New(fmt.Sprintf("Unknown type: %T", slice)) + } } diff --git a/slice_test.go b/slice_test.go index 9217c1b..118a6bc 100644 --- a/slice_test.go +++ b/slice_test.go @@ -25,3 +25,9 @@ func Test_Union(t *testing.T) { cc := Union(aa, bb) fmt.Println(cc) } + +func Test_Unique(t *testing.T) { + var str = []string{"1", "2", "2"} + ret, err := Unique(str) + fmt.Println(ret, err) +}