Skip to content

Instantly share code, notes, and snippets.

@johnwesonga
Created August 22, 2013 00:29
Show Gist options
  • Save johnwesonga/6301924 to your computer and use it in GitHub Desktop.
Save johnwesonga/6301924 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))
}
@Demznak
Copy link

Demznak commented Dec 21, 2023

@cr1cr1 The experiment was interesting Ж)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment