Generic types in Go
A struct can take a type parameter, and its methods reuse it.
type Stack[T any] struct {
items []T
}
func NewStack[T any]() *Stack[T] {
return &Stack[T]{}
}
func (s *Stack[T]) Push(item T) {
s.items = append(s.items, item)
}
func (s *Stack[T]) Pop() (T, bool) {
var zero T
if len(s.items) == 0 {
return zero, false
}
last := len(s.items) - 1
item := s.items[last]
s.items = s.items[:last]
return item, true
}
func (s *Stack[T]) Len() int { return len(s.items) }
How it works
- The parameter is declared on the type, not on each method.
- Methods cannot introduce new type parameters of their own.
- A constructor keeps the inference readable at the call site.
Keywords and builtins used here
anyappendboolfuncifintlenreturnstructtypevar
The run, in numbers
- Lines
- 24
- Characters to type
- 403
- Tokens
- 156
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 85 seconds.
Step 3 of 4 in Generics, step 15 of 19 in Interfaces & generics.