Created
April 23, 2018 01:21
-
-
Save valkheim/37125262f11794f9a7543be7d30b6e70 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 main | |
import ( | |
"fmt" | |
"reflect" | |
) | |
type Plop struct { | |
A string | |
} | |
func main() { | |
a := []string{"a", "b", "c", "b"} | |
b := []int64{1, 22, 3, 1, 2} | |
c := []Plop{Plop{A: "A"}, Plop{A: "A"}, Plop{A: "B"}} | |
unique(&a) | |
unique(&b) | |
unique(&c) | |
fmt.Println(a) | |
fmt.Println(b) | |
fmt.Println(c) | |
} | |
func unique(ptr interface{}) { | |
slice := reflect.ValueOf(ptr).Elem().Interface() | |
switch reflect.TypeOf(slice).Kind() { | |
case reflect.Slice: | |
seen := map[interface{}]bool{} | |
s := reflect.ValueOf(slice) | |
sliceType := reflect.TypeOf(s.Index(0).Interface()) | |
typedSlice := reflect.SliceOf(sliceType) | |
uniq := reflect.MakeSlice(typedSlice, 0, 0) | |
for i := 0; i < s.Len(); i++ { | |
if !seen[s.Index(i).Interface()] { | |
seen[s.Index(i).Interface()] = true | |
uniq = reflect.Append(uniq, s.Index(i)) | |
} | |
} | |
reflect.ValueOf(ptr).Elem().Set(uniq) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment