Created
September 3, 2021 07:05
-
-
Save nekomeowww/bf7507b78d652d3764fcb74e87786d9a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package util | |
import "reflect" | |
// UniqAny 去重 | |
func UniqAny(arrs interface{}) interface{} { | |
value := reflect.ValueOf(arrs) | |
// input value must be a slice | |
if value.Kind() != reflect.Slice { | |
panic("input must be a slice") | |
} | |
src := reflect.ValueOf(arrs) | |
dst := reflect.MakeSlice(src.Type(), 0, 0) | |
checked := make(map[interface{}]struct{}) | |
for i := 0; i < src.Len(); i++ { | |
elemv := src.Index(i) | |
if _, ok := checked[elemv.Interface()]; ok { | |
continue | |
} | |
checked[elemv.Interface()] = struct{}{} | |
dst = reflect.Append(dst, elemv) | |
} | |
return dst.Interface() | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package util | |
import "testing" | |
func TestUniqAny(t *testing.T) { | |
assert := assert.New(t) | |
arr := []int64{1, 1} | |
assert.Equal([]int64{1}, UniqAny(arr).([]int64)) | |
type example struct { | |
ID int64 | |
Name string | |
} | |
arr2 := []example{ | |
{ID: 1, Name: "1"}, | |
{ID: 1, Name: "1"}, | |
{ID: 2, Name: "1"}, | |
} | |
assert.Equal([]example{ | |
{ID: 1, Name: "1"}, | |
{ID: 2, Name: "1"}, | |
}, UniqAny(arr2).([]example)) | |
assert.PanicsWithValue("input must be a slice", func() { | |
UniqAny("") | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment