亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 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 關注
  • 129 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號