字符串切片去重
使用sort.String 方法对切片进行排序
使用发射机制 对切片进行排序
去重前的排序很重要
package main | |
import ( | |
"fmt" | |
"reflect" | |
"sort" | |
) | |
func main() { | |
b := []string{"12", "a", "b", "c", "a", "12"} | |
fmt.Println("去重前 ==>", b) | |
// 输出结果 [12 a b c a 12] | |
fmt.Println("去重后 ==>", Duplicate(b)) | |
// 输出结果 [12 a b c] | |
// 如果是int 那么使用 sort.Ints方法 | |
//c := []int{1, 1, 2, 4, 6, 7, 8, 4, 3, 2, 5, 6, 6, 8} | |
//sort.Ints(c) | |
//fmt.Println(DeleteDuplicateValue(c)) | |
} | |
func Duplicate(a []string) (ret []interface{}) { | |
sort.Strings(a) | |
va := reflect.ValueOf(a) | |
for i := 0; i < va.Len(); i++ { | |
if i > 0 && reflect.DeepEqual(va.Index(i-1).Interface(), va.Index(i).Interface()) { | |
continue | |
} | |
ret = append(ret, va.Index(i).Interface()) | |
} | |
return ret | |
} |