Go course

GenericsThe comparable Constraint

Go

Display

Theme

Generics · Test exercise

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 slices and maps packages contain plenty of ready-made generic functions, such as slices.Contains, slices.Index, and maps.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:

  1. func Berisi[T comparable](items []T, cari T) bool returns true if cari is in items.
  2. func Unik[T comparable](items []T) []T returns 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.

main.go
package main

import "fmt"

func Berisi[T comparable](items []T, cari T) bool {
	// TODO
	return false
}

func Unik[T comparable](items []T) []T {
	// TODO: gunakan map[T]bool untuk mencatat elemen yang sudah terlihat
	return nil
}

func main() {
	genre := []string{"fiksi", "sejarah", "fiksi", "sains", "sejarah"}
	fmt.Println("Ada genre sains?", Berisi(genre, "sains"))
	fmt.Println("Genre unik:", Unik(genre))

	peminjam := []int{1021, 1044, 1021, 1099}
	fmt.Println("Anggota 1099 meminjam?", Berisi(peminjam, 1099))
	fmt.Println("Peminjam unik:", Unik(peminjam))
}

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)