Golang Structure Comparison

The section "Go Programming Language Specification" on Comparison Operators makes me think that a structure containing only comparable fields should be comparable:

Structure values ​​are comparable if all their fields are comparable. Two structure values ​​are equal if their respective non-empty fields are equal.

Thus, I would expect the following code to compile, since all fields in the Student structure 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, the message failed to compile :

invalid operation: alice> = carol (operator> = not defined in the structure)

What am I missing?

+7
comparison struct go
source share
2 answers

You are right, the structures are comparable , but not ordered ( spec ):

The equality operators == and != Are applicable to comparable operands. The ordering operators < , <= , > and >= are applied to ordered operands.

...

  • Struct values ​​are compared if all their fields are comparable. Two structure values ​​are equal if their respective non-empty fields are equal.

>= is an ordered operator that is not comparable.

+14
source share

You must define the field that you are comparing in order to compile the program.

 if alice.Score >= carol.Score 

Then it compiles and prints

Alice> = Carol

+1
source share

All Articles