Home > other >  How to find overlapping values in list of objects in golang?
How to find overlapping values in list of objects in golang?

Time:06-09

package main

import (
    "fmt"
)

type Column struct {
    Name string `json:"name"`
    Type string `json:"type"`
}

func main() {

    a := []*Column{
        {Name: "a", Type: "int"},
        {Name: "b", Type: "int"},
    }
    b := []*Column{
        {Name: "a", Type: "int"},
        {Name: "c", Type: "string"},
    }
    c := []*Column{
        {Name: "a", Type: "string"},
        {Name: "d", Type: "int"},
        }
}

Need to find if there is any overlapping Name with different Type when comparing 2 list of objects, if not return false. Any suggestions for optimized logic?

 func check(obj1,obj2){
 // when comparing a and b it would return false as both Name="a" has identical Type="int"

// when comparing b and c it would return true as both Name="a" have different Types
}

CodePudding user response:

You can use a map to store and compare the keys:

package main

import (
    "fmt"
)

type Column struct {
    Name string `json:"name"`
    Type string `json:"type"`
}

func check(c1, c2 []*Column) bool {
    m := make(map[string]string)
    for _, col := range c1 {
        m[col.Name] = col.Type
    }
    for _, col := range c2 {
        if t, found := m[col.Name]; found && t != col.Type {
             return true
        }
    }
    return false
}

func main() {

    a := []*Column{
        {Name: "a", Type: "int"},
        {Name: "b", Type: "int"},
    }
    b := []*Column{
        {Name: "a", Type: "int"},
        {Name: "c", Type: "string"},
    }
    c := []*Column{
        {Name: "a", Type: "string"},
        {Name: "d", Type: "int"},
    }

    fmt.Println(check(a, b)) //false
    fmt.Println(check(a, c)) //true
    fmt.Println(check(b, c)) //true
}

Test it on Go playground

  • Related