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?
In Go language, you are allowed to compare two structures if they are of the same type and contain the same fields values with the help of == operator or DeeplyEqual() Method.
A struct (short for "structure") is a collection of data fields with declared data types. Golang has the ability to declare and create own data types by combining one or more types, including both built-in and user-defined types.
Slice values are deeply equal when all of the following are true: they are both nil or both non-nil, they have the same length, and either they point to the same initial entry of the same underlying array (that is, &x[0] == &y[0]) or their corresponding elements (up to length) are deeply equal.
You are correct, structs are comparable, but not ordered (spec):
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.
>=
is an ordered operator, not a comparable one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With