Golang去除slice和list的重复元素,非常有用的功能
转自:http://studygolang.com/articles/9622
Golang中,利用反射和interface就可以做到,不废话看代码
func main() { b := []string{"a","b","c","e","f","a","g","c"} sort.Strings(b) fmt.Println(Duplicate(b)) c := []int{1,1,2,4,6,7,8,3,5,8} sort.Ints(c) fmt.Println(Duplicate(c)) } func Duplicate(a interface{}) (ret []interface{}) { 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 }