在Go语言中比较多个结构字段

huangapple go评论79阅读模式
英文:

Comparing multiple struct fields in Go

问题

我想知道是否有一种通用的方法来对一个相当大的结构体进行单元测试,而不必写很多连续的if语句。我知道在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?

答案1

得分: 5

如果你需要检查所有字段,只需比较结构体:

type S struct {
    A int
    B float64
}

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

需要注意的是,如果你的结构体包含指针,可能会变得复杂,因为它们可能指向两个不同但相等的值。在这种情况下,你可以使用 reflect.DeepEqual

type S2 struct {
    A int
    B *float64
}

func main() {
    var f1, f2 = 3.14, 3.14
    // 输出 false,因为指针不同。
    fmt.Println(S2{1, &f1} == S2{1, &f2})
    // 输出 true。
    fmt.Println(reflect.DeepEqual(S2{1, &f1}, S2{1, &f2}))
}

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

除此之外,如果需要更复杂的操作,很可能需要定义自己的相等方法。

英文:

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.

huangapple
  • 本文由 发表于 2015年8月12日 19:45:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/31964309.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定