Generic Functions
Say you need a function that reverses a slice. Without generics, you'd have to write a separate version for []int, []string, []Produk, and so on. The bodies are identical; only the types differ.
Since Go 1.18, functions can take type parameters, written in square brackets before the regular parameters:
func Balik[T any](s []T) []T {
hasil := make([]T, 0, len(s))
for i := len(s) - 1; i >= 0; i-- {
hasil = append(hasil, s[i])
}
return hasil
}
Tis the name of the type parameter (by convention a single capital letter:T,K,V,E).anyis the constraint: it limits which types can be used forT.any(an alias forinterface{}) means any type at all.
Calling a generic function
Usually Go can figure out T from the arguments (type inference):
Balik([]int{1, 2, 3}) // T = int
Balik([]string{"a", "b"}) // T = string
Balik[float64]([]float64{1.5}) // T ditulis eksplisit (jarang perlu)
Every call is still strictly checked by the compiler. There are no silent conversions like there are when you use interface{}.
More than one type parameter
A function can have several type parameters:
func Petakan[T, U any](s []T, f func(T) U) []U {
// ubah setiap T menjadi U
}
panjang := Petakan([]string{"go", "gopher"}, func(s string) int { return len(s) })
// panjang = []int{2, 6}
Task
An online store team keeps filtering and transforming lists of products, orders, and customers. Write two generic functions in the editor:
func Filter[T any](items []T, cocok func(T) bool) []Treturns a new slice containing the elements for whichcocokreturnstrue, in the same order.func Petakan[T, U any](items []T, ubah func(T) U) []Ureturns a new slice of the same length containingubah(item)for each item.
Don't modify the input slice. The tests call both functions with int, string, and a struct.