How to find the difference between two slices in Go

Created
Modified

Using map cache

Creates a slice of slice values not included in the other given slices. An implementation is shown in the section below.

package main

import "fmt"

// difference returns the elements in `a` that aren't in `b`.
func difference(a, b []string) ([]string, error) {

  // uses empty struct (0 bytes) for map values.
  m := make(map[string]struct{}, len(b))

  // cached
  for _, v := range b {
    m[v] = struct{}{}
  }

  var diff []string
  for _, v := range a {
    if _, ok := m[v]; !ok {
      diff = append(diff, v)
    }
  }

  return diff, nil
}

func main() {

  s1 := []string{"a", "b"}
  s2 := []string{"b", "c", "d"}

  // find s1 strings not in s2
  s, _ := difference(s1, s2)
  fmt.Println(s)

  // find s2 strings not in s1
  s, _ = difference(s2, s1)
  fmt.Println(s)
}
[a]
[c d]

You can use reflect.TypeOf for any []T.

Using simple loops

Comparing two slices for missing element. For example,

package main

import "fmt"

func difference(a, b []string) ([]string, error) {
  var diff []string

  for _, m := range a {

    ok := false
    for _, n := range b {
      if m == n {
        ok = true
        break
      }
    }
    if !ok {
      diff = append(diff, m)
    }

  }

  return diff, nil
}

func main() {

  s1 := []string{"a", "b"}
  s2 := []string{"b", "c", "d"}

  // find s1 strings not in s2
  s, _ := difference(s1, s2)
  fmt.Println(s)

  // find s2 strings not in s1
  s, _ = difference(s2, s1)
  fmt.Println(s)
}
[a]
[c d]

Returns the new slice of filtered values.

Related Tags