Skip to content

Instantly share code, notes, and snippets.

@mercul3s
Last active October 30, 2017 23:06
Show Gist options
  • Save mercul3s/3614de6ddebd75ab11bcecbdf2e3f373 to your computer and use it in GitHub Desktop.
Save mercul3s/3614de6ddebd75ab11bcecbdf2e3f373 to your computer and use it in GitHub Desktop.
Determining unique values in a slice or array in Go requires the use of a map.
package main
import (
"fmt"
)
func appendUnique(list []string) []string {
// initialize a map of string keys and boolean values for
// keeping track of list entries we've seen.
uniqueKeys := make(map[string]bool)
// create an empty slice to hold our unique values.
uniqueList := []string{}
// Loop over the items in the list.
// Underscores are for discarding the index, in the case
// of the list, and keys, in the case of the map, as we
// don't need them to determine unique list entries.
for _, entry := range list {
// Check the map to see if it has our list entry.
// If not, the value will be false, and we should
// add it to the map and set it to true.
if _, value := uniqueKeys[entry]; !value {
uniqueKeys[entry] = true
uniqueList = append(uniqueList, entry)
}
}
// Return the list of unique values.
return uniqueList
}
func main() {
dupeList := []string{"hello", "hello", "world"}
dedupedList := appendUnique(dupeList)
// Starting list
fmt.Println(dupeList)
// Ending list
fmt.Println(dedupedList)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment