S SmartDocs
Série: Go go 72 linhas · Atualizado 2026-04-18

main.go

Go/part1-language/examples/09_generics/main.go

// Demonstrates generics: type parameters, constraints, generic types.
package main

import "fmt"

type Ordered interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64 |
		~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr |
		~float32 | ~float64 |
		~string
}

func Max[T Ordered](a, b T) T {
	if a > b {
		return a
	}
	return b
}

func Map[T, U any](s []T, f func(T) U) []U {
	out := make([]U, len(s))
	for i, v := range s {
		out[i] = f(v)
	}
	return out
}

func Filter[T any](s []T, keep func(T) bool) []T {
	out := s[:0]
	for _, v := range s {
		if keep(v) {
			out = append(out, v)
		}
	}
	return out
}

func Index[T comparable](s []T, x T) int {
	for i, v := range s {
		if v == x {
			return i
		}
	}
	return -1
}

type Set[T comparable] struct {
	m map[T]struct{}
}

func NewSet[T comparable]() *Set[T]    { return &Set[T]{m: make(map[T]struct{})} }
func (s *Set[T]) Add(v T)              { s.m[v] = struct{}{} }
func (s *Set[T]) Has(v T) bool         { _, ok := s.m[v]; return ok }
func (s *Set[T]) Len() int             { return len(s.m) }

func main() {
	fmt.Println(Max(1, 2), Max(2.5, 1.5), Max("a", "b"))

	doubled := Map([]int{1, 2, 3}, func(x int) int { return x * 2 })
	fmt.Println(doubled)

	odd := Filter([]int{1, 2, 3, 4, 5}, func(x int) bool { return x%2 == 1 })
	fmt.Println(odd)

	fmt.Println(Index([]string{"a", "b", "c"}, "b"))

	s := NewSet[string]()
	s.Add("go")
	s.Add("rust")
	s.Add("go")
	fmt.Println("set size:", s.Len(), "has go?", s.Has("go"))
}

Artigos relacionados