File tree Expand file tree Collapse file tree 2 files changed +27
-3
lines changed Expand file tree Collapse file tree 2 files changed +27
-3
lines changed Original file line number Diff line number Diff line change @@ -8,9 +8,14 @@ import (
8
8
9
9
// Subset returns true if all the keys of a are present
10
10
// in b and have the same values.
11
+ // If the corresponding value of a[k] is the zero value in
12
+ // b, Subset will skip comparing that value.
13
+ // This allows checking for the presence of map keys.
11
14
func Subset [T , U comparable ](a , b map [T ]U ) bool {
15
+ var uz U
12
16
for ka , va := range a {
13
- if vb , ok := b [ka ]; ! ok || va != vb {
17
+ ignoreZeroValue := va == uz
18
+ if vb , ok := b [ka ]; ! ok || (! ignoreZeroValue && va != vb ) {
14
19
return false
15
20
}
16
21
}
Original file line number Diff line number Diff line change @@ -11,8 +11,9 @@ func TestSubset(t *testing.T) {
11
11
t .Parallel ()
12
12
13
13
for idx , tc := range []struct {
14
- a map [string ]string
15
- b map [string ]string
14
+ a map [string ]string
15
+ b map [string ]string
16
+ // expected value from Subset
16
17
expected bool
17
18
}{
18
19
{
@@ -50,6 +51,24 @@ func TestSubset(t *testing.T) {
50
51
b : map [string ]string {"a" : "1" , "b" : "3" },
51
52
expected : false ,
52
53
},
54
+ // Zero value
55
+ {
56
+ a : map [string ]string {"a" : "1" , "b" : "" },
57
+ b : map [string ]string {"a" : "1" , "b" : "3" },
58
+ expected : true ,
59
+ },
60
+ // Zero value, but the other way round
61
+ {
62
+ a : map [string ]string {"a" : "1" , "b" : "3" },
63
+ b : map [string ]string {"a" : "1" , "b" : "" },
64
+ expected : false ,
65
+ },
66
+ // Both zero values
67
+ {
68
+ a : map [string ]string {"a" : "1" , "b" : "" },
69
+ b : map [string ]string {"a" : "1" , "b" : "" },
70
+ expected : true ,
71
+ },
53
72
} {
54
73
tc := tc
55
74
t .Run ("#" + strconv .Itoa (idx ), func (t * testing.T ) {
You can’t perform that action at this time.
0 commit comments