=` When Their Fields Are Comparable? " />
Go Struct Comparison: Unexpected Error
The Go Programming Language Specification states that structs with only comparable fields should be comparable. However, the following code fails to compile:
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") } }
The error message is:
invalid operation: alice >= carol (operator >= not defined on struct)This error contradicts the specification, as structs should be comparable if their fields are.
Explanation:
While the fields of the Student struct can be compared (using == and !=), they are not ordered. Ordering operators (<, <=, >, >=) can only be used on operands that are ordered, such as integers or strings.
The Go Programming Language Specification clearly states that structs are comparable but not ordered:
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.
Therefore, you cannot use >= to compare Student structs, even though their fields are comparable.
The above is the detailed content of Why Can't I Compare Go Structs with `>=` When Their Fields Are Comparable?. For more information, please follow other related articles on the PHP Chinese website!