Go course

GenericsGeneric Functions

Go

Display

Theme

Generics · Test exercise

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
}
  • T is the name of the type parameter (by convention a single capital letter: T, K, V, E).
  • any is the constraint: it limits which types can be used for T. any (an alias for interface{}) 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:

  1. func Filter[T any](items []T, cocok func(T) bool) []T returns a new slice containing the elements for which cocok returns true, in the same order.
  2. func Petakan[T, U any](items []T, ubah func(T) U) []U returns a new slice of the same length containing ubah(item) for each item.

Don't modify the input slice. The tests call both functions with int, string, and a struct.

main.go
package main

import "fmt"

type Produk struct {
	Nama  string
	Harga int
}

func Filter[T any](items []T, cocok func(T) bool) []T {
	// TODO: kumpulkan item yang cocok
	return nil
}

func Petakan[T, U any](items []T, ubah func(T) U) []U {
	// TODO: ubah setiap item
	return nil
}

func main() {
	produk := []Produk{
		{"Kaos", 75000},
		{"Jaket", 250000},
		{"Kaus kaki", 20000},
	}
	murah := Filter(produk, func(p Produk) bool { return p.Harga < 100000 })
	nama := Petakan(murah, func(p Produk) string { return p.Nama })
	fmt.Println("Produk murah:", nama)
}

Output

Go runtime not loaded yet

Press Run to see the output, or Submit to check your code.

Ctrl/Cmd + Enter: Run · Ctrl/Cmd + Shift + Enter: Submit · Ctrl/Cmd + S: tidy the code (gofmt)