Search code examples
gostructcomparison

Go struct comparison


The Go Programming Language Specification section on Comparison operators leads me to believe that a struct containing only comparable fields should be comparable:

Struct values are comparable if all their fields are comparable. Two struct values are equal if their corresponding non-blank fields are equal.

As such, I would expect the following code to compile since all of the fields in the "Student" struct are comparable:

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")
  }
}

However, it fails to compile with the message:

invalid operation: alice >= carol (operator >= not defined on struct)

What am I missing?


Solution

  • You are correct, structs are comparable, but not 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.

    >= is an ordered operator, not a comparable one.