Skip to content

Instantly share code, notes, and snippets.

@johnwesonga
Created August 22, 2013 00:29

Revisions

  1. johnwesonga created this gist Aug 22, 2013.
    24 changes: 24 additions & 0 deletions unique elements in a slice
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,24 @@
    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))
    }