Comparison operators 上的 Go 编程语言规范部分让我相信只包含可比较字段的结构应该是可比较的:
Struct values are comparable if all their fields are comparable. Two struct values are equal if their corresponding non-blank fields are equal.
因此,我希望以下代码能够编译,因为“Student”结构中的所有字段都是可比较的:
package main
type Student struct {
Name string // "String values are comparable and ordered, lexically byte-wise."
Score uint8 // "Integer values are comparable and ordered, in the usual way."
}
func main() {
alice := Student{"Alice", 98}
carol := Student{"Carol", 72}
if alice >= carol {
println("Alice >= Carol")
} else {
println("Alice < Carol")
}
}
但是,它 fails to compile与消息:
invalid operation: alice >= carol (operator >= not defined on struct)
我错过了什么?
最佳答案
你是对的,结构是comparable,但不是ordered(spec):
The equality operators
==
and!=
apply to operands that are comparable. The ordering operators<
,<=
,>
, and>=
apply to operands that are ordered....
- Struct values are comparable if all their fields are comparable. Two struct values are equal if their corresponding non-blank fields are equal.
>=
是一个有序的运算符,而不是一个可比的。
关于去结构比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39643251/