为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
三国纷争 2022-12-19 20:01:18
package mainimport (    "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}
查看完整描述

1 回答

?
撒科打诨

TA贡献1934条经验 获得超2个赞

您可以使用地图来存储和比较键:


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

}

Go playground上测试


查看完整回答
反对 回复 2022-12-19
  • 1 回答
  • 0 关注
  • 108 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信