Created
August 11, 2019 09:25
-
-
Save vlad-bezden/63eb851edb96a6eec98692c9dc0dfcf7 to your computer and use it in GitHub Desktop.
An example of how to find difference between two slices in Go. It uses map and empty struct (0 bytes) as a void to convert slice to map (kind of set).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
An example of how to find the difference between two slices. | |
This example uses empty struct (0 bytes) for map values. | |
*/ | |
package main | |
import ( | |
"fmt" | |
) | |
// empty struct (0 bytes) | |
type void struct{} | |
// missing compares two slices and returns slice of differences | |
func missing(a, b []string) []string { | |
// create map with length of the 'a' slice | |
ma := make(map[string]void, len(a)) | |
diffs := []string{} | |
// Convert first slice to map with empty struct (0 bytes) | |
for _, ka := range a { | |
ma[ka] = void{} | |
} | |
// find missing values in a | |
for _, kb := range b { | |
if _, ok := ma[kb]; !ok { | |
diffs = append(diffs, kb) | |
} | |
} | |
return diffs | |
} | |
func main() { | |
a := []string{"a", "b", "c", "d", "e", "f", "g"} | |
b := []string{"a", "c", "d", "e", "f", "g", "b"} | |
c := []string{"a", "b", "x", "y", "z"} | |
fmt.Println("a and b diffs", missing(a, b)) | |
fmt.Println("a and c diffs", missing(a, c)) | |
} | |
/* | |
Output: | |
a and b diffs [] | |
a and c diffs [x y z] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice approach with maps.
Unfortunately, this won't work if slices have repeating elements.
a := []string{"a", "b", "b"}
b := []string{"a", "a", "b"}
Still results in output
a and b diffs []
And having extra element in the first slice that is not present in the second slice goes unnoticed as well.
a := []string{"a", "b", "c"}
b := []string{"a", "b"}
Also results in output
a and b diffs []