The Go Programming Language Specification states that a struct comprising only comparable fields should be comparable. However, an issue arises when attempting to compare structs using ordered operators.
Consider the following code:
package main type Student struct { Name string Score uint8 } func main() { alice := Student{"Alice", 98} carol := Student{"Carol", 72} if alice >= carol { println("Alice >= Carol") } else { println("Alice < Carol") } }
Expectedly, this code compiles successfully due to the comparable fields. However, attempts to compare structs using the >= operator fail with:
invalid operation: alice >= carol (operator >= not defined on struct)
In Go, structs are comparable but not ordered. The specification clarifies this:
"The ordering operators <, <=, >, and >= apply to operands that are ordered."
Therefore, while structs can be compared for equality, they cannot be ordered using operators like >=, as seen in the example above.
The above is the detailed content of Why Can't You Compare Go Structs Using Order Operators?. For more information, please follow other related articles on the PHP Chinese website!