[Golang] Remove Duplicates From Slice or Array


How to remove duplicates from slice or array in Go?


There are many methods to do this [1]. My approach is to create a map [2] type and for each item in the slice/array, check if the item is in the map. If the item is in the map, the it is duplicate. If not in the map, save it in the map. After finished, the map contains no duplicates in the original slice/array.

The following is an example of above approach.

Run Code on Go Playground

package main

import (

func RemoveDuplicatesFromSlice(s []string) []string {
      m := make(map[string]bool)
      for _, item := range s {
              if _, ok := m[item]; ok {
                      // duplicate item
                      fmt.Println(item, "is a duplicate")
              } else {
                      m[item] = true

      var result []string
      for item, _ := range m {
              result = append(result, item)
      return result

func main() {
      var testSlice = []string{"Mike", "Matt", "Nancy", "Adam", "Jenny", "Nancy", "Carl"}
      resultSlice := RemoveDuplicatesFromSlice(testSlice)


[Mike Matt Nancy Adam Jenny Nancy Carl]
Nancy is a duplicate
[Jenny Carl Mike Matt Nancy Adam]

Tested on: Go Playground


[2]Go maps in action - The Go Blog