I am comparing two structs and want to ignore a single field while doing so.
type test struct {
name string
time string
}
func main() {
a := test{"testName", time.Now().Format(time.UnixTime)}
// after some time
b := test{"testName", time.Now().Format(time.UnixTime)}
fmt.Println(a.Name == b.Name) \\ returns true Desired outcome
fmt.Println(reflect.DeepEqual(a,b)) \\ returns false
}
reflect.DeepEqual()
does not allow for us to ignore a field and have manually done the comparison one field at a time.
What is the idiomatic way to go about this?
In Go language, you are allowed to compare two structures if they are of the same type and contain the same fields values with the help of == operator or DeeplyEqual() Method.
To find out if they are the same object, compare pointers to the two structs for equality. If you want to find out in general if they have the same value you have to do a deep comparison. This involves comparing all the members. If the members are pointers to other structs you need to recurse into those structs too.
Slice values are deeply equal when all of the following are true: they are both nil or both non-nil, they have the same length, and either they point to the same initial entry of the same underlying array (that is, &x[0] == &y[0]) or their corresponding elements (up to length) are deeply equal.
Checking for an empty struct in Go is straightforward in most cases. All you need to do is compare the struct to its zero value composite literal. This method works for structs where all fields are comparable.
Idiomatic way would be to implement your own func (o MyStruct) Equal(o2 MyStruct) bool
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With