函数
func RemoveDuplicates(slice interface{}) interface{} {
encountered := make(map[interface{}]bool)
resultSlice := reflect.MakeSlice(reflect.TypeOf(slice), 0, 0)
valSlice := reflect.ValueOf(slice)
for i := 0; i < valSlice.Len(); i++ {
val := valSlice.Index(i)
if !encountered[val.Interface()] {
encountered[val.Interface()] = true
resultSlice = reflect.Append(resultSlice, val)
}
}
return resultSlice.Interface()
}
单元测试
func TestRemoveDuplicates(t *testing.T) {
intSlice := []int{1, 2, 3, 4, 3, 2, 1}
uniqueInts := RemoveDuplicates(intSlice).([]int)
fmt.Println(intSlice)
fmt.Println(uniqueInts)
stringSlice := []string{"apple", "banana", "apple", "orange", "banana"}
uniqueStrings := RemoveDuplicates(stringSlice).([]string)
fmt.Println(stringSlice)
fmt.Println(uniqueStrings)
}