简介

我们时常有比较两个值是否相等的需求,最直接的方式就是使用==操作符,其实==的细节远比你想象的多,我在深入理解 Go 之==中有详细介绍,有兴趣去看看。但是直接用==,一个最明显的弊端就是对于指针,只有两个指针指向同一个对象时,它们才相等,不能进行递归比较。为此,reflect包提供了一个DeepEqual,它可以进行递归比较。但是相对的,reflect.DeepEqual不够灵活,无法提供选项实现我们想要的行为,例如允许浮点数误差。所以今天的主角go-cmp登场了。go-cmp是 Google 开源的比较库,它提供了丰富的选项。最初定位是用在测试中。

感谢thinkgos的推荐!

快速使用

先安装:

  1. $ go get github.com/com/google/go-cmp/cmp

后使用:

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/google/go-cmp/cmp"
  5. )
  6. type Contact struct {
  7. Phone string
  8. Email string
  9. }
  10. type User struct {
  11. Name string
  12. Age int
  13. Contact *Contact
  14. }
  15. func main() {
  16. u1 := User{Name: "dj", Age: 18}
  17. u2 := User{Name: "dj", Age: 18}
  18. fmt.Println("u1 == u2?", u1 == u2)
  19. fmt.Println("u1 equals u2?", cmp.Equal(u1, u2))
  20. c1 := &Contact{Phone: "123456789", Email: "dj@example.com"}
  21. c2 := &Contact{Phone: "123456789", Email: "dj@example.com"}
  22. u1.Contact = c1
  23. u2.Contact = c1
  24. fmt.Println("u1 == u2 with same pointer?", u1 == u2)
  25. fmt.Println("u1 equals u2 with same pointer?", cmp.Equal(u1, u2))
  26. u2.Contact = c2
  27. fmt.Println("u1 == u2 with different pointer?", u1 == u2)
  28. fmt.Println("u1 equals u2 with different pointer?", cmp.Equal(u1, u2))
  29. }

上面的例子中,我们将==cmp.Equal放在一起做个比较:

  • 在指针类型的字段Contact未设置时,u1 == u2cmp.Equal(u1, u2)都返回true
  • 两个结构的Contact字段都指向同一个对象时,u1 == u2cmp.Equal(u1, u2)都返回true
  • 两个结构的Contact字段指向不同的对象时,尽管这两个对象包含相同的内容,u1 == u2也返回了false。而cmp.Equal(u1, u2)可以比较指针指向的内容,从而返回true

以下是运行结果:

  1. u1 == u2? true
  2. u1 equals u2? true
  3. u1 == u2 with same pointer? true
  4. u1 equals u2 with same pointer? true
  5. u1 == u2 with different pointer? false
  6. u1 equals u2 with different pointer? true

高级选项

未导出字段

默认情况下,cmp.Equal()函数不会比较未导出字段(即字段名首字母小写的字段)。遇到未导出字段,cmp.Equal()直接panic。这一点与reflect.DeepEqual()有所不同,后者也会比较未导出的字段。

我们可以使用cmdopts.IgnoreUnexported选项忽略未导出字段,也可以使用cmdopts.AllowUnexported选项指定某些类型的未导出字段需要比较。

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/google/go-cmp/cmp"
  5. )
  6. type Contact struct {
  7. Phone string
  8. Email string
  9. }
  10. type User struct {
  11. Name string
  12. Age int
  13. contact *Contact
  14. }
  15. func main() {
  16. c1 := &Contact{Phone: "123456789", Email: "dj@example.com"}
  17. c2 := &Contact{Phone: "123456789", Email: "dj@example.com"}
  18. u1 := User{"dj", 18, c1}
  19. u2 := User{"dj", 18, c2}
  20. fmt.Println("u1 equals u2?", cmp.Equal(u1, u2))
  21. }

运行上面的代码会panic,因为cmd.Equal()比较的类型中有未导出字段contact。我们先使用cmdopts.IngoreUnexported忽略未导出字段:

  1. fmt.Println("u1 equals u2?", cmp.Equal(u1, u2, cmpopts.IgnoreUnexported(User{})))

我们在cmp.Equal()的调用中添加了选项cmpopts.IgnoreUnexported,选项参数传入User{}表示忽略User的直接未导出字段。导出字段中的未导出字段是不会被忽略的,除非显示指定该类型。如果我们将User稍作修改:

  1. type Address struct {
  2. Province string
  3. city string
  4. }
  5. type User struct {
  6. Name string
  7. Age int
  8. Address Address
  9. }
  10. func main() {
  11. u1 := User{"dj", 18, Address{}}
  12. u2 := User{"dj", 18, Address{}}
  13. fmt.Println("u1 equals u2?", cmp.Equal(u1, u2, cmpopts.IgnoreUnexported(User{})))
  14. }

注意,city字段未导出,这种情况下,使用cmpopts.IngoreUnexported(User{})还是会panic,因为cityAddress中的未导出字段,而非User的直接字段。

我们也可以使用cmdopts.AllowUnexported(User{})表示需要比较User的未导出字段:

  1. fmt.Println("u1 equals u2?", cmp.Equal(u1, u2, cmp.AllowUnexported(User{})))

浮点数比较

我们知道,计算机中浮点数的表示是不精确的,如果涉及到运算,可能会产生误差累计。此外,还有一个特殊的浮点数NaN(Not a Number),它与任何浮点数都不等,包括它自己。这样,有时候会出现一些反直觉的结果:

  1. package main
  2. import (
  3. "fmt"
  4. "math"
  5. "github.com/google/go-cmp/cmp"
  6. )
  7. type FloatPair struct {
  8. X float64
  9. Y float64
  10. }
  11. func main() {
  12. p1 := FloatPair{X: math.NaN()}
  13. p2 := FloatPair{X: math.NaN()}
  14. fmt.Println("p1 equals p2?", cmp.Equal(p1, p2))
  15. f1 := 0.1
  16. f2 := 0.2
  17. f3 := 0.3
  18. p3 := FloatPair{X: f1 + f2}
  19. p4 := FloatPair{X: f3}
  20. fmt.Println("p3 equals p4?", cmp.Equal(p3, p4))
  21. p5 := FloatPair{X: 0.1 + 0.2}
  22. p6 := FloatPair{X: 0.3}
  23. fmt.Println("p5 equals p6?", cmp.Equal(p5, p6))
  24. }

运行程序,输出:

  1. p1 equals p2? false
  2. p3 equals p4? false
  3. p5 equals p6? true

是不是很反直觉?NaN不等于NaN0.1 + 0.2竟然不等于0.3!前者是由于标准的规定,后者是浮点数的表示不精确导致的计算误差。

奇怪的是第三组表示,为什么直接用字面量运算就不会导致误差呢?实际上,在 Go 语言中这些字面量的运算直接是在编译器完成的,可以做到精确。如果先赋值给浮点类型的变量,就像第 2 组所示,受限于变量的存储空间,就会存在误差。

关于这一点,我这里再顺带介绍一个知识点。我们都知道使用const定义常量时可以不指定类型,这种常量被称为无类型的常量,它的值可以超出正常数值的表示范围,可以相互进行的运算。只是不能赋值给超过其类型表示范围的普通变量

  1. package main
  2. import "fmt"
  3. const (
  4. _ = 1 << (10 * iota)
  5. KB // 1024
  6. MB // 1048576
  7. GB // 1073741824
  8. TB // ‭1099511627776‬
  9. PB // ‭1125899906842624‬
  10. EB // ‭1152921504606846976‬
  11. ZB // ‭1180591620717411303424‬
  12. YB // ‭1208925819614629174706176‬
  13. )
  14. func main() {
  15. // constant ‭1180591620717411303424‬ overflows int
  16. // fmt.Println(ZB)
  17. // constant 1208925819614629174706176 overflows uint64
  18. // var mem uint64 = YB
  19. fmt.Println(YB / ZB)
  20. }

后面ZBYB都已经超出了uint64的表示范围。直接使用时,如fmt.Println(ZB)编译器会自动将其转为int类型,但是它的值超出了int的表示范围,所以编译报错。赋值时也是如此。

go-cmp提供比较浮点数的选项,我们希望两个NaN的比较返回true,两个浮点数相差不超过一定范围就认为它们相等:

  • cmpopts.EquateNaNs():两个NaN比较,返回true
  • cmpopts.EquateApprox(fraction, margin):这个选项有两个参数,第二个参数比较好理解,如果两个浮点数的差的绝对值小于margin则认为它们相等。第一个参数的含义是取两个数绝对值的较小者,乘以fraction,如果两个数的差的绝对值小于这个数即|x-y| ≤ max(fraction*min(|x|, |y|), margin),则认为它们相等。如果fractionmargin同时设置,只需要满足一个就行了

例如:

  1. type FloatPair struct {
  2. X float64
  3. Y float64
  4. }
  5. func main() {
  6. p1 := FloatPair{X: math.NaN()}
  7. p2 := FloatPair{X: math.NaN()}
  8. fmt.Println("p1 equals p2?", cmp.Equal(p1, p2, cmpopts.EquateNaNs()))
  9. f1 := 0.1
  10. f2 := 0.2
  11. f3 := 0.3
  12. p3 := FloatPair{X: f1 + f2}
  13. p4 := FloatPair{X: f3}
  14. fmt.Println("p3 equals p4?", cmp.Equal(p3, p4, cmpopts.EquateApprox(0.1, 0.001)))
  15. }

运行输出:

  1. p1 equals p2? true
  2. p3 equals p4? true

Nil

默认情况下,如果一个切片变量值为nil,另一个是使用make创建的长度为 0 的切片,那么go-cmp认为它们是不等的。同样的,一个map变量值为nil,另一个是使用make创建的长度为 0 的map,那么go-cmp也认为它们不等。我们可以指定cmpopts.EquateEmpty选项,让go-cmp认为它们相等:

  1. func main() {
  2. var s1 []int
  3. var s2 = make([]int, 0)
  4. var m1 map[int]int
  5. var m2 = make(map[int]int)
  6. fmt.Println("s1 equals s2?", cmp.Equal(s1, s2))
  7. fmt.Println("m1 equals m2?", cmp.Equal(m1, m2))
  8. fmt.Println("s1 equals s2 with option?", cmp.Equal(s1, s2, cmpopts.EquateEmpty()))
  9. fmt.Println("m1 equals m2 with option?", cmp.Equal(m1, m2, cmpopts.EquateEmpty()))
  10. }

切片

默认情况下,两个切片只有当长度相同,且对应位置上的元素都相等时,go-cmp才认为它们相等。如果,我们想要实现无序切片的比较(即只要两个切片包含相同的值就认为它们相等),可以使用cmpopts.SortedSlice选项先对切片进行排序,然后再进行比较:

  1. func main() {
  2. s1 := []int{1, 2, 3, 4}
  3. s2 := []int{4, 3, 2, 1}
  4. fmt.Println("s1 equals s2?", cmp.Equal(s1, s2))
  5. fmt.Println("s1 equals s2 with option?", cmp.Equal(s1, s2, cmpopts.SortSlices(func(i, j int) bool { return i < j })))
  6. m1 := map[int]int{1: 10, 2: 20, 3: 30}
  7. m2 := map[int]int{1: 10, 2: 20, 3: 30}
  8. fmt.Println("m1 equals m2?", cmp.Equal(m1, m2))
  9. fmt.Println("m1 equals m2 with option?", cmp.Equal(m1, m2, cmpopts.SortMaps(func(i, j int) bool { return i < j })))
  10. }

对于map来说,由于本身就是无序的,所以map比较差不多是下面这种形式。没有上面的顺序问题:

  1. func compareMap(m1, m2 map[int]int) bool {
  2. if len(m1) != len(m2) {
  3. return false
  4. }
  5. for k, v := range m1 {
  6. if v != m2[k] {
  7. return false
  8. }
  9. }
  10. return true
  11. }

cmpopts.SortMaps会将map[K]V类型按照键排序,生成一个[]struct{K, V}的切片,然后逐个比较。

SortSlicesSortMaps都需要提供一个比较函数less,函数必须是func(T, T) bool这种形式,切片的元素类型必须可以赋值给T类型,map的键也必须可以赋值给T类型。

自定义Equal方法

对于有些类型来说,go-cmp内置的比较结果不符合我们的要求,这时我们可以自定义Equal方法来比较该类型。例如我们想要表示IP地址的字符串比较时127.0.0.1localhost相等:

  1. package main
  2. type NetAddr struct {
  3. IP string
  4. Port int
  5. }
  6. func (a NetAddr) Equal(b NetAddr) bool {
  7. if a.Port != b.Port {
  8. return false
  9. }
  10. if a.IP != b.IP {
  11. if a.IP == "127.0.0.1" && b.IP == "localhost" {
  12. return true
  13. }
  14. if a.IP == "localhost" && b.IP == "127.0.0.1" {
  15. return true
  16. }
  17. return false
  18. }
  19. return true
  20. }
  21. func main() {
  22. a1 := NetAddr{"127.0.0.1", 5000}
  23. a2 := NetAddr{"localhost", 5000}
  24. a3 := NetAddr{"192.168.1.1", 5000}
  25. fmt.Println("a1 equals a2?", cmp.Equal(a1, a2))
  26. fmt.Println("a1 equals a3?", cmp.Equal(a1, a3))
  27. }

很简单,只需要给想要自定义比较操作的类型提供一个Equal()方法即可,方法接受该类型的参数,返回一个bool表示是否相等。如果我们将上面的Equal()方法注释掉,那么比较输出都是false

自定义比较器

如果go-cmp默认的行为无法满足我们的需求,我们可以针对某些类型自定义比较器。我们使用cmp.Comparer()传入比较函数,比较函数必须是func (T, T) bool这种形式。所有能转为T类型的值,都会调用该函数进行比较。所以如果T是接口类型,那么可能传给比较函数的参数的实际类型并不相同,只是它们都实现了T接口。我们使用Comparer()重构一下上面的程序:

  1. type NetAddr struct {
  2. IP string
  3. Port int
  4. }
  5. func compareNetAddr(a, b NetAddr) bool {
  6. if a.Port != b.Port {
  7. return false
  8. }
  9. if a.IP != b.IP {
  10. if a.IP == "127.0.0.1" && b.IP == "localhost" {
  11. return true
  12. }
  13. if a.IP == "localhost" && b.IP == "127.0.0.1" {
  14. return true
  15. }
  16. return false
  17. }
  18. return true
  19. }
  20. func main() {
  21. a1 := NetAddr{"127.0.0.1", 5000}
  22. a2 := NetAddr{"localhost", 5000}
  23. fmt.Println("a1 equals a2?", cmp.Equal(a1, a2))
  24. fmt.Println("a1 equals a2 with comparer?", cmp.Equal(a1, a2, cmp.Comparer(compareNetAddr)))
  25. }

这种方式与上面介绍的自定义Equal()方法有些类似,但更灵活。有时,我们要自定义比较操作的类型定义在第三方包中,这样就无法给它定义Equal方法。这时,我们就可以采用自定义Comparer的方式。

Exporter

从前面的介绍我们知道默认情况下,未导出字段会导致cmp.Equal()直接panic。前面也介绍过两种方式处理未导出字段,这里再介绍一种方式——cmp.Exporter。通过传入一个函数func (t reflec.Type) bool,返回传入的类型是否比较其未导出字段。例如,下面代码中,我们指定需要比较类型User的未导出字段:

  1. type Contact struct {
  2. Phone string
  3. Email string
  4. }
  5. type User struct {
  6. Name string
  7. Age int
  8. contact Contact
  9. }
  10. func allowUnExportedInType(t reflect.Type) bool {
  11. if t.Name() == "User" {
  12. return true
  13. }
  14. return false
  15. }
  16. func main() {
  17. c1 := Contact{Phone: "123456789", Email: "dj@example.com"}
  18. c2 := Contact{Phone: "123456789", Email: "dj@example.com"}
  19. u1 := User{"dj", 18, c1}
  20. u2 := User{"dj", 18, c2}
  21. fmt.Println("u1 equals u2?", cmp.Equal(u1, u2, cmp.Exporter(allowType)))
  22. }

cmp.Exporter的使用不多,且可以通过AllowUnexported选项来实现。

转换器

转换器可以将特定类型的值转为另一种类型的值。转换器有很多用法,下面介绍两种。

忽略字段

如果我们想忽略结构中的某些字段,我们可以定义转换,返回一个不设置这些字段的对象:

  1. type User struct {
  2. Name string
  3. Age int
  4. }
  5. func omitAge(u User) string {
  6. return u.Name
  7. }
  8. type User2 struct {
  9. Name string
  10. Age int
  11. Email string
  12. Address string
  13. }
  14. func omitAge2(u User2) User2 {
  15. return User2{u.Name, 0, u.Email, u.Address}
  16. }
  17. func main() {
  18. u1 := User{Name: "dj", Age: 18}
  19. u2 := User{Name: "dj", Age: 28}
  20. fmt.Println("u1 equals u2?", cmp.Equal(u1, u2, cmp.Transformer("omitAge", omitAge)))
  21. u3 := User2{Name: "dj", Age: 18, Email: "dj@example.com"}
  22. u4 := User2{Name: "dj", Age: 28, Email: "dj@example.com"}
  23. fmt.Println("u3 equals u4?", cmp.Equal(u3, u4, cmp.Transformer("omitAge", omitAge2)))
  24. }

如果一个类型,我们只关心一个字段,忽略其它字段,那么直接返回这个字段就行了,如上面的omitAge。如果该类型有多个字段,我们只忽略很少的字段,我们要返回一个同样的类型,不设置忽略的字段即可,如上面的omitAge2

转换值

上面我们介绍了如何使用自定义Equal()方法和Comparer比较器的方式来实现 IP 地址的比较。实际上转换器也可以实现同样的效果,我们可以将localhost转换为127.0.0.1

  1. type NetAddr struct {
  2. IP string
  3. Port int
  4. }
  5. func transformLocalhost(a NetAddr) NetAddr {
  6. if a.IP == "localhost" {
  7. return NetAddr{IP: "127.0.0.1", Port: a.Port}
  8. }
  9. return a
  10. }
  11. func main() {
  12. a1 := NetAddr{"127.0.0.1", 5000}
  13. a2 := NetAddr{"localhost", 5000}
  14. fmt.Println("a1 equals a2?", cmp.Equal(a1, a2, cmp.Transformer("localhost", transformLocalhost)))
  15. }

遇到IPlocalhost的对象,将其转换为IP127.0.0.1的对象。

Diff

除了能比较两个值是否相等,go-cmp还能汇总两个值的不同之处,方便我们查看。上面介绍的选项都可以用在Diff中:

  1. type Contact struct {
  2. Phone string
  3. Email string
  4. }
  5. type User struct {
  6. Name string
  7. Age int
  8. Contact *Contact
  9. }
  10. func main() {
  11. c1 := &Contact{Phone: "123456789", Email: "dj@example.com"}
  12. c2 := &Contact{Phone: "123456879", Email: "dj2@example.com"}
  13. u1 := User{Name: "dj", Age: 18, Contact: c1}
  14. u2 := User{Name: "dj2", Age: 18, Contact: c2}
  15. fmt.Println(cmp.Diff(u1, u2))
  16. }

我们着重介绍一下输出的格式:

  1. main.User{
  2. - Name: "dj",
  3. + Name: "dj2",
  4. Age: 18,
  5. Contact: &main.Contact{
  6. - Phone: "123456789",
  7. + Phone: "123456879",
  8. - Email: "dj@example.com",
  9. + Email: "dj2@example.com",
  10. },
  11. }

相信使用过 SVN 或对 Linux 的diff命令熟悉的童鞋对上面的格式应该不会陌生。我们可以这样认为,第一个对象为原来的版本,第二个对象为新的版本。这样上面的输出我们可以想象成如何将对象从原来的版本变为新版本。没有前缀的行不需要改变,前缀为-的行表示新版本删除了这一行,前缀+表示新版本增加了这一行。

总结

go-cmp库大大地方便两个值的比较操作。源码中大量使用我们之前介绍过的选项模式,提供给使用者简洁、一致的接口。这种设计思想也值得我们学习、借鉴。本文介绍了这是go-cmp的一部分内容,还有一些特性如过滤器感兴趣可自行探索。

大家如果发现好玩、好用的 Go 语言库,欢迎到 Go 每日一库 GitHub 上提交 issue😄

参考

  1. go-cmp GitHub:https://github.com/google/go-cmp
  2. Go 每日一库 GitHub:https://github.com/go-quiz/go-daily-lib