Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bernardolm/971231e6066616a658853fe0fbef5cab to your computer and use it in GitHub Desktop.
Save bernardolm/971231e6066616a658853fe0fbef5cab to your computer and use it in GitHub Desktop.
Go code that ensures elements in a slice are unique
package main
import "fmt"
func uniqueNonEmptyElementsOf(s []string) []string {
unique := make(map[string]bool, len(s))
us := make([]string, len(unique))
for _, elem := range s {
if len(elem) != 0 {
if !unique[elem] {
us = append(us, elem)
unique[elem] = true
}
}
}
return us
}
func main() {
names := []string{"John", "Peter", "Jim", "John", "Ken", "Pete", "Jimmy"}
fmt.Println(uniqueNonEmptyElementsOf(names))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment