Comparing multiple structural fields in Go

I was wondering if there is a general way to modulate testing values โ€‹โ€‹of a rather large structure without having to write many if statements one after another. I know that in Go we can use table-based unit tests, but I have not yet found how we can implement this table-based approach using structures.

My goal is to create a structure, do something with it and unit test the new values โ€‹โ€‹of the structure. Does anyone know how I can achieve this using table-driven tests or if there is a better way to do this?

+4
source share
1 answer

If you need to check all the fields, just compare the structures:

type S struct { A int B float64 } func main() { fmt.Println(S{1, 3.14} == S{1, 3.14}) // Prints true. } 

Note that if your structures contain pointers, this can become tricky, as they can point to two different but equal values. In this case, you can use reflect.DeepEqual :

 type S2 struct { A int B *float64 } func main() { var f1, f2 = 3.14, 3.14 // Prints false because the pointers differ. fmt.Println(S2{1, &f1} == S2{1, &f2}) // Prints true. fmt.Println(reflect.DeepEqual(S2{1, &f1}, S2{1, &f2})) } 

Playground: http://play.golang.org/p/G24DbRDQE8 .

Anything more interesting than this is likely to require you to define your own methods of equality.

+2
source

All Articles