Go Generics
Generics allow you to write functions and data structures that work with any type, while still keeping the code type-safe.
Go specifically avoided supporting
genericsto keep the language simple. But later the team added support of generics in golang.
Basic Generic Function
Instead of writing separate functions for int, float64, and string, you can use a type parameter like [T any].
The hardest part to understand from this code is MapKeys[K comparable, V any]. Here, the keyword K comparable act as strict implementation for a map key. It should support bit operation like equal to, etc. V any is the value of the map and it can be anything. including a interface{}.
Generic Structs
You can also create structs that hold any type.
Type Constraints
Sometimes you don't want "any" type, but only types that support certain operations (like addition).
Why use Generics?
- Reduce Code Duplication: No need to write the same logic for multiple types.
- Type Safety: Unlike using
any(the empty interface), generics catch errors at compile time. - Cleaner Data Structures: You can build generic stacks, queues, or linked lists that work with any type you put in them.