The comparable Constraint
With the any constraint, you can only do things that work for every type: copy a value, store it, pass it to another function. You can't compare two T values with ==, because some types aren't comparable (slices, maps, functions).
func Indeks[T any](s []T, cari T) int {
for i, v := range s {
if v == cari { // error: incomparable types in type set
return i
}
}
return -1
}
The fix: use the built-in comparable constraint, which only allows types that support == and != (numbers, strings, bools, pointers, channels, arrays, and structs whose fields are all comparable).
func Indeks[T comparable](s []T, cari T) int {
for i, v := range s {
if v == cari {
return i
}
}
return -1
}
Indeks([]string{"go", "rust", "zig"}, "zig") // 2
comparable and maps
Map keys must be comparable. That's why comparable also shows up when a generic function builds a map keyed by T:
func Kelompokkan[K comparable, V any](items []V, kunci func(V) K) map[K][]V {
hasil := make(map[K][]V)
for _, it := range items {
k := kunci(it)
hasil[k] = append(hasil[k], it)
}
return hasil
}
The standard
slicesandmapspackages contain plenty of ready-made generic functions, such asslices.Contains,slices.Index, andmaps.Keys. In this exercise we write our own versions to understand how they work.
Task
A library system keeps lots of lists: book codes, member IDs, genres. Write two generic functions:
func Berisi[T comparable](items []T, cari T) boolreturnstrueifcariis initems.func Unik[T comparable](items []T) []Treturns a new slice with duplicates removed, keeping the order of first appearance. For example,Unik([]string{"fiksi", "sejarah", "fiksi", "sains"})→[fiksi sejarah sains].
Hint: Unik can use a map[T]bool to keep track of the elements it has already seen.