1、现实代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // []string 去重 func RemoveDuplicate(list []string) []string { // 这个排序很关键 sort.Strings(list) i := 0 var newlist = []string{""} for j := 0; j < len(list); j++ { if strings.Compare(newlist[i], list[j]) == -1 { newlist = append(newlist, list[j]) i++ } } return newlist } |
2、Test
1 2 3 4 5 | func TestRemoveDuplicate(t *testing.T) { var list = []string{"a", "q", "b", "a", "c", "f", "c", "d", "e", "s"} list = RemoveDuplicate(list) t.Logf("%s", list) } |
3、结果
1 2 3 4 | #在测试目录下执行 go test -v === RUN TestRemoveDuplicate TestRemoveDuplicate: strings_test.go:8: [ a b c d e f q s] --- PASS: TestRemoveDuplicate (0.00s) |