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
minandmaxfunctions, plusslices.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:
func Total[T Angka](nilai []T) Treturns the sum of every element (0for an empty slice).func RataRata[T Angka](nilai []T) float64returns the average as afloat64(0for an empty slice). Hint:float64(total).func Terbesar[T cmp.Ordered](nilai []T) (T, bool)returns the largest element andtrue; for an empty slice, return the zero value ofTandfalse. It must also work forstring.