Lesson 50 of 60 · Go
Advanced Generics – Type Sets & Constraints
Duration: 25 minutes
Type Sets (Go 1.18+)
This lesson explains the main concept clearly with beginner-friendly examples and background so you can learn why the code works.
A type set enumerates allowed types for a type parameter.
type Number interface { ~int | ~int64 | ~float64 }
func Sum[T Number](vals []T) T { var s T; for _, v := range vals { s += v }; return s }
Interface constraints with methods
type Stringer interface { String() string }
func Join[T Stringer](elems []T, sep string) string {
var sb strings.Builder
for i, e := range elems {
if i > 0 { sb.WriteString(sep) }
sb.WriteString(e.String())
}
return sb.String()
}
Using generic structs with methods
type Stack[T any] struct { items []T }
func (s *Stack[T]) Push(v T) { s.items = append(s.items, v) }
func (s *Stack[T]) Pop() (T, bool) {
if len(s.items) == 0 { var zero T; return zero, false }
idx := len(s.items) - 1
v := s.items[idx]
s.items = s.items[:idx]
return v, true
}