去结构比较

mae*_*ics 14 comparison struct go

关于比较运算符的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")
  }
}
Run Code Online (Sandbox Code Playgroud)

但是,它无法使用以下消息进行编译:

无效操作:alice> = carol(operator> =未在struct上定义)

我错过了什么?

Tim*_*per 27

你是对的,结构是可比的,但没有订购(spec):

等于运算符==并!=适用于可比较的操作数.排序运营商<,<=,>和>=适用于排序操作数.

...

  • 如果所有字段都具有可比性,则结构值可比较.如果相应的非空白字段相等,则两个结构值相等.

>= 是一个有序的运算符,而不是类似的运算符.