When NOT to Use Generics
Generics are a powerful tool, but Go is designed to keep code simple and readable. Generics add a layer of abstraction, so use them only when the benefit is clear.
Signs that generics fit
- You're writing exactly the same code for several types, and the only thing that changes is the type: functions over slices or maps (
Filter,Unik,Keys), or general-purpose data structures (Stack,Antrean,Cache). - The function doesn't care about the element type; it only moves, stores, or compares values.
Signs you DON'T need generics
1. A regular interface is enough. If the function only calls methods, just accept an interface:
// Berlebihan:
func Cetak[T fmt.Stringer](v T) { fmt.Println(v.String()) }
// Lebih sederhana dan sama kuatnya:
func Cetak(v fmt.Stringer) { fmt.Println(v.String()) }
(The first version is overkill; the second is simpler and just as powerful.)
2. There's only one type. Don't write a generic function "just in case" when it's only ever called with int today. Write the concrete version; switch to generics when a second use actually shows up.
3. The behavior differs per type. If the function body branches on type (switch any(v).(type)), that's a sign you really need several different functions, or an interface with a method.
4. The signature gets hard to read. func Proses[K comparable, V any, S ~[]V, M ~map[K]S](...) might be technically correct, but your teammates will have to read it several times.
Rule of thumb: write concrete code first. When you find yourself copying the same function for a second or third type, that's when generics are worth considering.
Try it yourself
The example in the editor shows two approaches side by side: a generic Keys function (a good fit, since it works for any map) and an Umumkan function that just accepts an interface. Run it with Run, then try adding a new type that satisfies the Pengumuman interface. Notice that you don't have to change Umumkan at all.