Home > Article > Backend Development > Why Does Struct Comparison Fail in Go Despite Comparable Fields?
Despite conforming to the Go specification on struct comparability, where all fields of a struct are comparable, the following code fails to compile:
type Student struct { Name string Score uint8 } func main() { alice := Student{"Alice", 98} carol := Student{"Carol", 72} if alice >= carol { // Error: "invalid operation" println("Alice >= Carol") } else { println("Alice < Carol") } }
The key to understanding this failure lies in distinguishing between comparability and orderability.
While the Student struct's fields are indeed comparable, the >= operator is an ordering operator, not a comparable one. This distinction is explicitly mentioned in the Go specification, where struct values are defined as "comparable if all their fields are comparable," but only "equal if their corresponding non-blank fields are equal." Ordering is not mentioned in this context.
The misconception that led to this compile-time error stems from assuming that comparability implies orderability. In Go, these are distinct concepts. While structs can be compared for equality, they cannot be ordered by default unless their fields provide a specific ordering relation.
The above is the detailed content of Why Does Struct Comparison Fail in Go Despite Comparable Fields?. For more information, please follow other related articles on the PHP Chinese website!