-
-
Save bernardolm/971231e6066616a658853fe0fbef5cab to your computer and use it in GitHub Desktop.
Go code that ensures elements in a slice are unique
This file contains 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
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