SHARE
TWEET

Untitled

a guest Aug 23rd, 2019 65 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. An example of how to find the difference between two slices.
  3. This example uses empty struct (0 bytes) for map values.
  4. */
  5.  
  6. package main
  7.  
  8. import (
  9.     "fmt"
  10. )
  11.  
  12. // empty struct (0 bytes)
  13. type void struct{}
  14.  
  15. // missing compares two slices and returns slice of differences
  16. func missing(a, b []string) []string {
  17.     // create map with length of the 'a' slice
  18.     ma := make(map[string]void, len(a))
  19.     diffs := []string{}
  20.     // Convert first slice to map with empty struct (0 bytes)
  21.     for _, ka := range a {
  22.         ma[ka] = void{}
  23.     }
  24.     // find missing values in a
  25.     for _, kb := range b {
  26.         if _, ok := ma[kb]; !ok {
  27.             diffs = append(diffs, kb)
  28.         }
  29.     }
  30.     return diffs
  31. }
  32.  
  33. func main() {
  34.     a := []string{"a", "b", "c", "d", "e", "f", "g"}
  35.     b := []string{"a", "c", "d", "e", "f", "g", "b"}
  36.     c := []string{"a", "b", "x", "y", "z"}
  37.     fmt.Println("a and b diffs", missing(a, b))
  38.     fmt.Println("a and c diffs", missing(a, c))
  39. }
  40.  
  41. /*
  42. Output:
  43.  
  44. a and b diffs []
  45. a and c diffs [x y z]
  46. */
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top