Generics in Go: one function, many types

Learn Go · Beginner · 10 min · After Interfaces in Go: behaviour without classes

How do you write a function once for many types?

  1. 1Guess

    package main
    
    import (
    	"cmp"
    	"fmt"
    )
    
    func Max[T cmp.Ordered](a, b T) T {
    	if a > b {
    		return a
    	}
    	return b
    }
    
    func main() {
    	fmt.Println(Max(3, 7))
    	fmt.Println(Max("apple", "banana"))
    }
    
    What does this program print?
  2. 2Read

    Type parameters

    A function can take type parameters in square brackets: func Max[T cmp.Ordered](a, b T) T. T is a stand-in type. The part after it is a constraint: it says which types are allowed. Most of the time Go infers T from the arguments, so you call Max(3, 7) with no brackets. any allows every type. comparable allows types you can compare with ==.

  3. 3Code

    Map and Filter

    1 / 2
    package main
    
    import "fmt"
    
    func Map[T, U any](xs []T, f func(T) U) []U {
    	out := make([]U, 0, len(xs))
    	for _, x := range xs {
    		out = append(out, f(x))
    	}
    	return out
    }
    
    func Filter[T any](xs []T, keep func(T) bool) []T {
    	var out []T
    	for _, x := range xs {
    		if keep(x) {
    			out = append(out, x)
    		}
    	}
    	return out
    }
    
    func main() {
    	nums := []int{1, 2, 3, 4, 5}
    	fmt.Println(Map(nums, func(n int) string { return fmt.Sprint(n * n) }))
    	fmt.Println(Filter(nums, func(n int) bool { return n%2 == 1 }))
    }
    

    Read the program. What will it print?

    Run it in the playground

  4. 4Read

    Your own constraints and types

    A constraint is an interface. It can list types with a union: type Number interface { ~int | ~float64 }. The ~ also allows types built on them, such as type Celsius float64. A generic type takes parameters too: type Stack[T any] struct { items []T }. Methods repeat the parameter in the receiver: func (s *Stack[T]) Push(x T).

  5. 5Code

    Sum and a generic Stack

    1 / 2
    package main
    
    import "fmt"
    
    type Number interface {
    	~int | ~float64
    }
    
    func Sum[T Number](xs []T) T {
    	var total T
    	for _, x := range xs {
    		total += x
    	}
    	return total
    }
    
    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
    	}
    	last := s.items[len(s.items)-1]
    	s.items = s.items[:len(s.items)-1]
    	return last, true
    }
    
    func main() {
    	fmt.Println(Sum([]int{1, 2, 3}))
    	fmt.Println(Sum([]float64{1.5, 2.5}))
    
    	var s Stack[string]
    	s.Push("a")
    	s.Push("b")
    	v, ok := s.Pop()
    	fmt.Println(v, ok)
    	s.Pop()
    	v, ok = s.Pop()
    	fmt.Printf("%q %t\n", v, ok)
    }
    

    Read the program. What will it print?

    Run it in the playground

  6. 6Fix

    package main
    
    import "fmt"
    
    type Number interface {
    	~int | ~float64
    }
    
    func Sum[T Number](xs []T) T {
    	var total T
    	for _, x := range xs {
    		total += x
    	}
    	return total
    }
    
    func main() {
    	fmt.Println(Sum([]string{"a", "b"}))
    }
    
    Why does the compiler reject this call to Sum?
  7. 7Say it back

  8. 8Mission · 10 min

    Write Contains[T comparable](xs []T, x T) bool. Call it with a slice of ints and a slice of strings and print the results.

    go run .

Free AI coding tools to practise with

  1. AgentRouter Free Credits

    Free AI coding credits: $25 per daily check-in and $50 per invite

    No cardVerified

  2. Cursor Free Plan

    Cursor Agent with limited agent and chat requests, $0/month

    No cardVerified

  3. Cline Free Models

    Try select models free in Cline via rotating promotions with a usage quota

    No cardVerified

All free ai coding tools →

Common questions

When should I use generics in Go?
Use them when the same code must work for several types and the body does not depend on which one, such as Map, Filter, Max or a Stack. If you only have one type, or the types share behaviour that a small interface can describe, plain code or an interface is simpler. Do not add type parameters before you see duplication.
What does ~int mean in a Go constraint?
The tilde means any type whose underlying type is int, not only int itself. So a type you declare as type Age int satisfies ~int, but it would not satisfy a constraint that lists plain int. Constraints such as Number use ~int and ~float64 so that your own named number types work with generic functions like Sum.
What is the difference between any and comparable?
The any constraint allows every type, but the function body can then do very little with a value of that type. The comparable constraint allows only types that support == and !=, such as numbers, strings and structs of them. Use comparable when you must compare values, for example to search a slice or to use them as map keys.

Sources

Measured with go1.27.4 darwin/arm64 on 2026-12-03

Published Dec 3, 2026 · Updated Dec 3, 2026

Never miss new offers and news

New tools, credits, and AI news are added regularly. Pick how you want to hear about them.

Telegram channel

Join @aifree_dev and get new free AI offers and news right in your Telegram feed.

Browser notifications

Turn on push notifications and get an alert on this device whenever something new is posted. No account needed.

Email newsletter

A weekly digest of new, changed and expiring free AI offers. Double opt-in, one-click unsubscribe. See the latest issue.

Unsubscribe anytime. Privacy

Frequently asked questions

What is aifree.dev?

aifree.dev helps everyone access AI through a curated directory of free AI tools, API credits, free tiers, and startup programs for coding, image, voice, video, and students - verified regularly.

How are offers presented?

Each offer includes its access details, free models when available, and expiration information when provided. Limited-time deals stay visible so they are easy to compare.

Do education and startup programs need verification?

Yes. Providers usually ask students to verify their status with a school email, student ID, or a program like the GitHub Student Pack, and ask startups to verify company details such as age, funding, or website. Check each offer’s claim page for the exact requirements.

What kinds of free AI offers are listed?

Free tiers and free trials from AI providers, free API credits, startup and student programs, and free tools for coding, image generation, voice, and video.

How can I suggest a tool or report a broken link?

Use the submit form: paste the offer page URL and a short note. A person checks every submission before anything is listed. Broken links and changed terms go through the same form.

Know a good one?

Tell us about an AI tool worth knowing. Found a broken link? We want to hear that too.

Submit an offer