Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save atc0005/ff1ca51ea5f3cec0715702604dd93b24 to your computer and use it in GitHub Desktop.
Save atc0005/ff1ca51ea5f3cec0715702604dd93b24 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