如何在 golang 的对象列表中找到重叠值?

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"},

        }

}

比较 2 个对象列表时需要查找是否有重叠的 Name 和不同的 Type,如果没有则返回 false。对优化逻辑有什么建议吗?


 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

}


三国纷争
浏览 109回答 1
1回答

撒科打诨

您可以使用地图来存储和比较键:package mainimport (    "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}在Go playground上测试
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go