Go course

GenericsCustom Constraints and cmp.Ordered

Go

Display

Theme

Generics · Test exercise

Custom Constraints and cmp.Ordered

What if a generic function needs to add up values? The + operator doesn't work for every type, and comparable isn't enough either. We need a constraint that lists the types that are allowed.

Interfaces as type lists

In Go, a constraint is an interface. Besides methods, a constraint interface can contain a union of types separated by |:

type Angka interface {
	int | int64 | float64
}

func Jumlah[T Angka](nilai []T) T {
	var total T // zero value T, yaitu 0
	for _, v := range nilai {
		total += v // boleh, karena semua tipe di Angka mendukung +
	}
	return total
}

An interface like this can only be used as a constraint, not as the type of an ordinary variable.

The ~ sign: including derived types

In earlier chapters we often defined new types on top of basic ones, for example:

type Rupiah int
type Celsius float64

Rupiah is a different type from int, so it doesn't satisfy the constraint int | int64 | float64. The tilde ~ means "any type whose underlying type is this one":

type Angka interface {
	~int | ~int64 | ~float64
}

Jumlah([]Rupiah{15000, 20000}) // OK: tipe dasar Rupiah adalah int, hasilnya Rupiah

cmp.Ordered

For the comparisons <, >, <=, >=, the standard cmp package already provides the cmp.Ordered constraint, which covers every integer type, floating-point type, and string (including types derived from them):

import "cmp"

func Min[T cmp.Ordered](a, b T) T {
	if a < b {
		return a
	}
	return b
}

Since Go 1.21 there are built-in min and max functions, plus slices.Max. This exercise has you write your own versions to practice constraints.

Task

A coffee shop's point-of-sale app processes sales data of several types (int, float64, and Rupiah). The Angka constraint and the Rupiah type are already provided. Write:

  1. func Total[T Angka](nilai []T) T returns the sum of every element (0 for an empty slice).
  2. func RataRata[T Angka](nilai []T) float64 returns the average as a float64 (0 for an empty slice). Hint: float64(total).
  3. func Terbesar[T cmp.Ordered](nilai []T) (T, bool) returns the largest element and true; for an empty slice, return the zero value of T and false. It must also work for string.
main.go
package main

import (
	"cmp"
	"fmt"
)

type Angka interface {
	~int | ~int64 | ~float64
}

type Rupiah int

func Total[T Angka](nilai []T) T {
	// TODO
	var total T
	return total
}

func RataRata[T Angka](nilai []T) float64 {
	// TODO
	return 0
}

func Terbesar[T cmp.Ordered](nilai []T) (T, bool) {
	// TODO
	var nol T
	return nol, false
}

func main() {
	penjualan := []Rupiah{18000, 25000, 22000}
	fmt.Println("Total penjualan:", Total(penjualan))
	fmt.Println("Rata-rata:", RataRata(penjualan))

	suhu := []float64{88.5, 91.0, 90.2}
	if maks, ok := Terbesar(suhu); ok {
		fmt.Println("Suhu air tertinggi:", maks)
	}
	if menu, ok := Terbesar([]string{"latte", "americano", "mocha"}); ok {
		fmt.Println("Menu terakhir (abjad):", menu)
	}
}

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)