Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing multiple struct fields in Go

I was wondering if there is a generic way of unit testing the values of a rather large struct without having to write many if statements below each other. I know in Go we can use table-driven unit tests, but I have not yet found how we can implement this table-driven approach with structs.

My goal is to create a struct, do something with it, and unit test the new values of the struct. Does anybody know how I can achieve this with table-driven tests or if there's a better way to do it?

like image 628
jbrulmans Avatar asked Aug 12 '15 11:08

jbrulmans


1 Answers

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

type S struct {
    A int
    B float64
}

func main() {
    fmt.Println(S{1, 3.14} == S{1, 3.14}) // Prints true.
}

Notice though that if your structs contain pointers, that may get tricky because they may point to two different but equal values. In that 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 fancier than that will most probably require you to define your own equality methods.

like image 114
Ainar-G Avatar answered Oct 17 '22 00:10

Ainar-G