How to compare to structs in golang but ignore undefined fields
05:26 09 Jan 2026

I want to compare 2 structs in golang and consider them equal if all fields with a value are equal while ignoring fields which are undefined in either struct.

Take the following example:

type MyType struct {
    foo string
    bar string
}

func main() {
    a := MyType{foo: "foo"}
    b := MyType{foo: "foo", bar: "bar"}
    c := MyType{foo: "foo", bar: "baz"}
}

The goal would be for a to be equal to both b and c, but b and c should not be equal.

Is there a builtin way for making this comparison?

go struct compare equality