Home > other >  How can I determine struct equality based on fields and not struct types in Golang?
How can I determine struct equality based on fields and not struct types in Golang?

Time:08-05

I am currently using the go-cmp package to compare struct equality. For testing purposes I have the need to compare two different types of structs that should have the same fields with the same values.

As a minimal example I am running into the issue where the cmp.Equal() function returns false for different types, even though they have the same fields and values.

type s1 struct {
    Name string
}

type s2 struct {
    Name string
}

p1 := s1{Name: "John"}
p2 := s2{Name: "John"}

fmt.Println(cmp.Equal(p1, p2)) // false

This is understandable since the two types are different but is there a way to instruct cmp.Equal() to ignore the types and only look at fields?

CodePudding user response:

I don't know if you can omit types during comparison, but if 2 struct types have identical fields, you can convert one to the other type, so this won't be an issue:

p1 := s1{Name: "John"}
p2 := s2{Name: "John"}

fmt.Println(cmp.Equal(p1, p2)) // false
fmt.Println(cmp.Equal(p1, s1(p2))) // true

Try it on the Go Playground.

CodePudding user response:

What I would suggest for long term, is to have a function IsS1EqualToS2 and check the fields one-by-one:

func IsS1EqualToS2(s1 s1, s2 s2) bool {
    if s1.Name != s2.Name {
        return false
    }
    return true
}

and use as: IsS1EqualToS2(p1, p2)

  • Related