Created
March 1, 2016 16:02
-
-
Save andrewkroh/39b60a7df6d3b473de4d to your computer and use it in GitHub Desktop.
Deduplicate a Slice of Strings in Go
This file contains hidden or 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
// Deduplicate returns a new slice with duplicates values removed. | |
func Deduplicate(s []string) []string { | |
if len(s) == 0 { | |
return s | |
} | |
result := []string{} | |
seen := make(map[string]struct{}) | |
for _, val := range s { | |
if _, ok := seen[val]; !ok { | |
result = append(result, val) | |
seen[val] = val | |
} | |
} | |
return result | |
} |
You can also optimize if len(s) == 0
to if len(s) <= 1
as a slice of length 1 cannot have duplicates.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
seen[val] = val
should beseen[val] = struct{}{}