Comparable in Golang
Radhakishan Surwase
Senior Technical Lead | Golang Expert | Microservices Architect | Cloud-Native Enthusiast | Kubernetes & Docker | Building Scalable Systems
In Go, the comparable constraint is used to specify that a type can be compared using the standard comparison operators (==, <, <=, >, >=). This is an important concept in Go because some types, such as slices, maps, and functions, are not comparable.
When a generic function or type is defined in Go, you can use the comparable keyword to ensure that only comparable types can be used with that function or type. For example:
func max[T comparable](x, y T) T
? ? if x > y {
? ? ? ? return x
? ? }
? ? return y
}
In the above example, the max function takes two arguments of type T and returns the maximum of the two values. The comparable keyword ensures that only types that are comparable can be used with this function.
Here are some examples of types that are comparable in Go:
领英推荐
And here are some examples of types that are not comparable:
When defining a custom type, you can ensure that it satisfies the comparable constraint by making sure that all its fields are comparable types. For example:
type Person struct
? ? Name string
? ? Age ?int
}
// This function is not allowed, because Person is not a comparable type
// func max[T comparable](x, y T) T {
// ? ? if x > y {
// ? ? ? ? return x
// ? ? }
// ? ? return y
// }
// This function is allowed, because we only compare the Age field which
// is an int (a comparable type)
func older(p1, p2 Person) Person {
? ? if p1.Age > p2.Age {
? ? ? ? return p1
? ? }
? ? return p2
}
In the above example, the Person struct is not a comparable type because it contains a non-comparable field (Name is a string). Therefore, we cannot use it with the max function. However, we can define a custom function older that compares two Person values based on their Age field, which is an integer (a comparable type).
Happy Coding..... !!!