Golang代码学习之Comparable
背景
今天github上学习 uber的开源库atomic, 看到一段有意思的代码,以前从没注意过,涉及到Comparable的相关知识,今天来具体学习下
相关代码
1 | type nocmp [0]func() |
这段代码的意思是声明一个struct,此struct和镶嵌它的struct都不可以被compare。那么如何判断type是否可以compare呢,首先golang官方有一个说明文档, 里边具体阐释了各种基础类型的情况,涉及到此处的一段话
1 | Slice, map, and function values are not comparable. However, as a special case, a slice, map, or function value may be compared to the predeclared identifier nil. Comparison of pointer, channel, and interface values to nil is also allowed and follows from the general rules above. |
也就是说,这三种类型只能和nil做比较,不能做其他比较。所以代码里使用了一个无参的function来阻止比较。另外还有一个点就是,这个struct因为是长度为0的数组,所以占用空间是0,这个也是需要学习的点。
1 | type nocmp [0]func() |
output
1 | comparable:false, size: 0 |
另外需要注意的一点是,虽然interface是可以比较的,但是如果实现interface的是不可比较的类型,那么也会异常
1 | A comparison of two interface values with identical dynamic types causes a run-time panic if values of that type are not comparable. This behavior applies not only to direct interface value comparisons but also when comparing arrays of interface values or structs with interface-valued fields. |
所以以后做interface的比较的时候还是小心一点,当然,大部分情况下我们只会和nil做比较,就不会有这个问题了