Skip to content

Instantly share code, notes, and snippets.

@andrewkroh
Created March 1, 2016 16:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewkroh/39b60a7df6d3b473de4d to your computer and use it in GitHub Desktop.
Save andrewkroh/39b60a7df6d3b473de4d to your computer and use it in GitHub Desktop.
Deduplicate a Slice of Strings in Go
// 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
}
@jaredririe
Copy link

seen[val] = val should be seen[val] = struct{}{}

@jaredririe
Copy link

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