go - 有没有办法将结构与 slice 字段与零值结构进行比较?

标签 go struct comparison

我有一个带有 slice 字段的 Favorites 结构:

type Favorites struct {
    Color string
    Lunch string
    Place string
    Hobbies []string 
}

我有一个包含另一个结构的 Person:

type Person struct {
    Name string
    Favorites Favorites
}

我想看看 Favorites 字段是否设置在 Person 上。对于其他类型的字段,例如字符串或整数,我会将该字段与零值(分别为“”或 0)进行比较。

如果我尝试如下所示与零进行比较,我会得到错误 invalid operation: p2.Favorites == zeroValue (struct containing []string cannot be compare):

p2 := Person{Name: "Joe"}

zeroValue := Favorites{}
if p2.Favorites == zeroValue {
    fmt.Println("Favorites not set")
}

这与规范 (https://golang.org/ref/spec#Comparison_operators) 中定义的相匹配。

除了乏味地比较每个字段(并且必须记住在结构发生变化时更新它)之外,还有什么方法可以进行这种比较吗?

一个选项是使 Favorites 字段成为指向结构的指针而不是结构本身,然后只与 nil 进行比较,但这是在一个大型代码库中,所以我不想在这种情况下进行可能影响深远的更改.

https://play.golang.org/p/d0NSp8eBes

最佳答案

According to this ,您可以使用 reflect.DeepEqual(),但可能应该自己编写:

type Favorites struct {
    Color string
    Lunch string
    Place string
    Hobbies []string 
}

func (favs *Favorites) Equals(other *Favorites) bool {
    color_eq := favs.Color == other.Color
    lunch_eq := favs.Lunch == other.Lunch
    place_eq := favs.Place == other.Place
    hobbies_eq := len(favs.Hobbies) == len(other.Hobbies)
    if hobbies_eq {  // copy slices so sorting won't affect original structs
        f_hobbies := make([]string, len(favs.Hobbies))
        o_hobbies := make([]string, len(other.Hobbies))
        copy(favs.Hobbies, f_hobbies)
        copy(other.Hobbies, o_hobbies)
        sort.Strings(f_hobbies)
        sort.Strings(o_hobbies)
        for index, item := range f_hobbies {
            if item != o_hobbies[index] {
                hobbies_eq = false
            }
        }
    }
    return (color_eq && lunch_eq && place_eq && hobbies_eq)
}

然后调用它:

p2.Favorites.Equals(zeroValue)

关于go - 有没有办法将结构与 slice 字段与零值结构进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41290735/

相关文章:

go - 通过 channel 将值发送到多个 go routines

go - 更新 : Send the origin header with js websockets

C - 对函数内部的 Struct* 数组的副本进行排序

c# - 如何为 P/Invoke 声明指向结构的指针?

PHP & MySQL : use a table for a filter list for another table

flutter - 仅在 Flutter 中按日期比较 DateTime 对象

docker - host to add/usr/bin/host to scratch 由 Go binary 组成的 Dockerfile?

go - Golang 的引用表达式类型

c++ - 类中的结构

c - 缓冲区与字符串比较(没有换行符)