К основному содержимому
УРОК 12 ИЗ 16

Дженерики

2 Теория

Зачем

Раньше одну и ту же функцию для int, float64 и string приходилось копировать или использовать any (теряя проверку типов). С Go 1.18 есть обобщения.

func Map[T, R any](items []T, f func(T) R) []R {
    out := make([]R, 0, len(items))
    for _, it := range items { out = append(out, f(it)) }
    return out
}

func Filter[T any](items []T, ok func(T) bool) []T {
    var out []T
    for _, it := range items { if ok(it) { out = append(out, it) } }
    return out
}

squares := Map([]int{1, 2, 3}, func(x int) int { return x * x })      // [1 4 9]
lens := Map([]string{"go", "rust"}, func(s string) int { return len(s) })
evens := Filter([]int{1, 2, 3, 4}, func(x int) bool { return x%2 == 0 })

Ограничения типов

import "cmp"

type Number interface{ ~int | ~int64 | ~float64 }

func Sum[T Number](xs []T) T {
    var s T
    for _, x := range xs { s += x }
    return s
}
func Max[T cmp.Ordered](a, b T) T { if a > b { return a }; return b }

type Stack[T any] struct{ items []T }
func (s *Stack[T]) Push(x T) { s.items = append(s.items, x) }
func (s *Stack[T]) Pop() (T, bool) {
    var zero T
    if len(s.items) == 0 { return zero, false }
    x := s.items[len(s.items)-1]
    s.items = s.items[:len(s.items)-1]
    return x, true
}

Не усложняйте: если функция работает с одним типом, дженерик не нужен. Стандартная библиотека уже содержит slices и maps (slices.Sort, slices.Contains, maps.Keys).