Generics when to use them and when it’s not:
Common useful cases:
- Implementation of Data Structures that help us factor out the element type if we used the binary tree, linked list, …
- Function working with slices, maps and channels
Common not useful cases:
- When calling a method of the type argument Consider a function that receives an io.Writer and calls the Write method, for example:
func foo[T io.Writer](w T) {
b := getBytes()
_, _ = w.Write(b)
}
In this case, using generics won’t bring any value to our code whatsoever. We should make the w argument an io.Writer directly.
- When it makes our code more complex, Generics are never mandatory, and as Go developers, we have lived without them for more than a decade. If we’re writing generic functions or structures and we figure out that it doesn’t make our code clearer, we should probably reconsider our decision for that particular use case.