Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare structs except one field golang

Tags:

struct

go

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?

like image 232
Gaurav Raghuvanshy Avatar asked Nov 06 '17 10:11

Gaurav Raghuvanshy


People also ask

Can you compare structs in Golang?

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.

Can you compare two structs?

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.

How can I check if two slices are equal?

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.

How do you check if a struct is empty in Golang?

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.


1 Answers

Idiomatic way would be to implement your own func (o MyStruct) Equal(o2 MyStruct) bool method.

like image 164
Alexander Trakhimenok Avatar answered Sep 21 '22 19:09

Alexander Trakhimenok