

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 3
click for more info
Not enough gems
Cost: 6 gems
1: Generics in Go
incomplete
2: Why Generics?
incomplete
3: Constraints
incomplete
4: Interface Type Lists
incomplete
5: Parametric Constraints
incomplete
6: Naming Generic Types
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
When generics were released, a new way of writing interfaces was also released at the same time!
Traditional interfaces in Go are method-based: a type satisfies an interface if it has the required methods.
With generics, we also got type-set (type-list) interfaces. Instead of listing methods, they list the concrete (or underlying) types that are allowed. These are mostly used as constraints on type parameters.
For example, to use < and > on a type parameter T, the compiler must know T is ordered. A type-list interface spells out exactly which types count as ordered:
// Ordered matches any type that supports <, <=, >, and >=.
type Ordered interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr |
~float32 | ~float64 |
~string
}
// Because T is constrained by Ordered, the compiler knows
// that < is valid for any T used with this function.
func Min[T Ordered](a, b T) T {
if a < b {
return a
}
return b
}