How to do struct comparison in Go ?

Answer • 1 Asked • Jan 14 2020
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?

Write your answer...

On a mission to build Next-Gen Community Platform for Developers