Generic Types
Type parameters aren't just for functions. Structs (and other types) can be generic too, which is perfect for data structures like queues, stacks, or caches that can hold anything.
type Pasangan[K comparable, V any] struct {
Kunci K
Nilai V
}
p := Pasangan[string, int]{Kunci: "level", Nilai: 12}
When you create a value of a generic type, you usually have to spell out its type arguments (Pasangan[string, int]), because there are no function arguments to infer them from.
Methods on generic types
Methods repeat the type parameter on the receiver, without the constraint:
type Antrean[T any] struct {
items []T
}
func (a *Antrean[T]) Masuk(v T) {
a.items = append(a.items, v)
}
func (a *Antrean[T]) Keluar() (T, bool) {
var nol T
if len(a.items) == 0 {
return nol, false
}
depan := a.items[0]
a.items = a.items[1:]
return depan, true
}
Notice the var nol T pattern for getting the zero value of any type. It comes in handy when there's no value to return.
Methods can't have extra type parameters of their own.
func (a *Antrean[T]) Petakan[U any]()isn't valid; use a regular function for cases like that.
The zero value Antrean[int]{} works right away, because you can append to a nil slice.
Task
A text editor needs an undo feature, and an RPG needs a deck of cards. Both can use a stack (last in, first out). Complete Stack[T any]:
func (s *Stack[T]) Push(v T)putsvon top.func (s *Stack[T]) Pop() (T, bool)takes and removes the top element; if the stack is empty, return the zero value andfalse.func (s *Stack[T]) Intip() (T, bool)looks at the top element without removing it; if the stack is empty, return the zero value andfalse.func (s *Stack[T]) Len() intreturns the number of elements.
The zero value Stack[T]{} must work right away.