登录
首页 >  Golang >  Go问答

在golang的对象列表中如何检测重复值?

来源:stackoverflow

时间:2024-02-14 12:51:18 169浏览 收藏

本篇文章向大家介绍《在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 个对象列表时,需要查找是否存在不同类型的重叠名称,如果没有则返回 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
}

正确答案


您可以使用映射来存储和比较密钥:

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上测试

今天关于《在golang的对象列表中如何检测重复值?》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>