【发布时间】:2018-07-14 05:37:36
【问题描述】:
Comparison operators 上的 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")
}
}
但是,它fails to compile 带有消息:
无效操作:alice >= carol(操作符 >= 未在结构上定义)
我错过了什么?
【问题讨论】:
标签: go struct comparison