jbrulmans
jbrulmans

Reputation: 1005

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?

Upvotes: 6

Views: 4104

Answers (1)

Ainar-G
Ainar-G

Reputation: 36279

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.

Upvotes: 5

Related Questions