Go编程语言规范中比较运算符一节让我相信,一个只包含可比较字段的结构体应该是可比较的:
如果一个结构体的所有字段都是可比较的,则其值是可比较的。如果两个结构体值对应的非空白字段相等,则它们相等。
因此,我期望以下代码能够编译,因为"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")
}
}
然而,它编译失败,并显示以下消息:
invalid operation: alice >= carol (operator >= not defined on struct)
我漏掉了什么?