如何检查地图是否可以在Golang中部分匹配其他地图

Suppose, I have two map[string]([]string)

 MAP1 := map[string]([]string) {
    "User" : []string{"11", "33"},
    "Type" : []string{"A"},
    }


MAP2 := map[string]([]string) {
    "User" : []string{"11", "17"},
    "Type" : []string{"B"},
    }

Here, MAP1 matches MAP2 partially.

User = 11 is in both map

How can I check this in a easy way?

For example:

package main

import "fmt"

func Max(x, y int) int {
    if x > y {
        return x
    }
    return y
}

func Intersect(as, bs []string) []string {
    i := make([]string, 0, Max(len(as), len(bs)))
    for _, a := range as {
        for _, b := range bs {
            if a == b {
                i = append(i, a)
            }
        }
    }
    return i
}

func main() {

    MAP1 := map[string][]string{
        "User": []string{"11", "33"},
        "Type": []string{"A"},
    }

    MAP2 := map[string][]string{
        "User": []string{"11", "17"},
        "Type": []string{"B"},
    }

    MAP3 := make(map[string][]string)

    for k, _ := range MAP1 {
        MAP3[k] = Intersect(MAP1[k], MAP2[k])
    }

    fmt.Println(MAP3) // MAP3 contains commonalities between MAP1 and MAP2
}

Note that this solution does not exploit any potential performance optimizations (like assuming that the string arrays will be sorted in some way, or else) and hence has a runtime performance of O(m • n2), where:

  • m is the number of keys in the map (assumed to be the same for both maps)
  • n is the number of elements in each string slice (assumed to be the same for both corresponding map entries)

Which is okay but not great.

You check if the cardinality of the intersection between those two maps is greater than 0.

See for instance set.go Intersect in deckarep/golang-set.

// Returns a new set containing only the elements
// that exist only in both sets.
//
// Note that the argument to Intersect
// must be of the same type as the receiver
// of the method. Otherwise, Intersect will
// panic.
Intersect(other Set) Set