去结构比较

标签 go struct comparison

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/

相关文章:

c - 指向结构指针的指针

Golang 将 float64 转换为 int 错误

windows - 登录用户,Windows,在 Golang 中

c - #pragma pack 与 Intel C 的 -fpack-struct

MySQL从一张表中查询 - 选择同一字段两次

algorithm - 给定 M 最大值的每个基于比较的排序算法的时间复杂度的下限 Ω(nlogn)

python - Python 中的位置比较

pointers - 附加到其他 slice 内的结构上的 slice 不持久

go - 在 [for] 循环中处理返回值

python - 在Python中解压ripemd160结果