Go generics programs let you write one function or type that works for many types, such as int, float64 and string, without copying code. In this post, you will write fifteen short programs with their exact output and the logic explained in comments, covering Max, Map, Filter, Reduce, a generic stack, a set and custom constraints.
You should first finish our Go function programs and Go interface programs, because constraints are written as interfaces. For the theory, read our Go generics examples guide. All programs were tested on Go 1.27.
What are Go Generics Programs?
Go generics programs use type parameters. A type parameter is a placeholder type written in square brackets, like [T any]. When you call the function, Go fills in the real type for you.
Think of a cookie cutter. The shape stays the same, but you can press it into chocolate dough, plain dough or ginger dough. A generic function is the cutter, and the type is the dough.
Why Go Generics Programs Matter
Before generics, you had to write MaxInt, MaxFloat and MaxString as three separate functions, or use any and lose type safety. Go generics programs fix both problems.
- Less code: one
Mapfunction works for every slice type. - Type safety: the compiler still checks every call, so no runtime type checks.
- Reusable types: one
Stack[T]works for ints, strings or structs. - Interviews: Map, Filter, Reduce and a generic stack are among the most asked Go programs.
How Go Generics Programs Work
A generic function has two lists. The type parameter list in square brackets names the types, and the normal list in round brackets names the values. Each type parameter has a constraint that says which types are allowed.

The table below lists the common constraints used in this post.
| Constraint | Where | Allows |
|---|---|---|
| any | built in | Every type |
| comparable | built in | Types that work with == and != |
| cmp.Ordered | cmp package | Types that work with < and > |
| ~int | your own interface | int and any type built on int |
| Number | your own interface | A list of number types |
Basic Go Generics Programs
These first Go generics programs show a generic function, type inference and the cmp.Ordered constraint. Start with Program 1, because it is the smallest generic function you can write.
Program 1: Your First Generic Function
package main
import "fmt"
// PrintAll prints every item of a slice, whatever the item type is.
// [T any] means "T can be any type". T is the type parameter.
func PrintAll[T any](items []T) {
for _, item := range items { // _ skips the index we do not need
fmt.Print(item, " ")
}
fmt.Println()
}
func main() {
PrintAll([]int{1, 2, 3}) // here T is int
PrintAll([]string{"red", "green"}) // here T is string
PrintAll([]float64{9.5, 7.25}) // here T is float64
}
1 2 3
red green
9.5 7.25
You write PrintAll once, and it works for three slice types. When you call it, Go looks at the slice and fills in T for you. So you do not need a separate function for ints, strings and floats.
Program 2: Generic Max with cmp.Ordered
package main
import (
"cmp"
"fmt"
)
// Max returns the bigger of two values.
// T is the type parameter, cmp.Ordered is its constraint: it allows < and >.
func Max[T cmp.Ordered](first, second T) T {
if first > second {
return first
}
return second
}
func main() {
fmt.Println(Max(3, 7)) // T is inferred as int
fmt.Println(Max(2.5, 1.5)) // T is inferred as float64
fmt.Println(Max("apple", "kiwi")) // strings compare letter by letter
fmt.Println(Max[int](10, 4)) // you can also pass T yourself
}
7
2.5
kiwi
10
Go looks at the arguments and works out T for you. This is called type inference. Both arguments must have the same type, because they are both T. “kiwi” wins because “k” comes after “a”.
Program 3: Find an Item with comparable
package main
import "fmt"
// Index returns the position of target in items, or -1 if it is missing.
// comparable allows == so we can compare items.
func Index[T comparable](items []T, target T) int {
for i, item := range items { // i is the position, item is the value
if item == target {
return i
}
}
return -1 // not found
}
func main() {
fmt.Println(Index([]int{10, 20, 30}, 20))
fmt.Println(Index([]string{"go", "java"}, "rust"))
}
1
-1
The loop checks each item with == and returns its position when it matches. If the loop ends with no match, the function returns -1. The standard library already has slices.Index, which works the same way, but writing it yourself is a common interview warm-up.
Program 4: Sum Numbers with a Custom Constraint
package main
import "fmt"
// Number lists the types Sum accepts. | means "or".
// The ~ means "this type or any type built on it".
type Number interface {
~int | ~int64 | ~float64
}
// Rupees is a named type whose underlying type is int.
type Rupees int
// Sum adds up all the numbers in the slice.
func Sum[T Number](numbers []T) T {
var total T // zero value of T: 0 for numbers
for _, number := range numbers {
total += number // allowed because every type in Number supports +
}
return total
}
func main() {
fmt.Println(Sum([]int{1, 2, 3}))
fmt.Println(Sum([]float64{1.5, 2.25}))
fmt.Println(Sum([]Rupees{100, 250})) // works only because of ~int
}
6
3.75
350
Number is a constraint that lists the allowed types. Because every type in it supports +, the compiler lets you write total += number. Without the ~, Rupees would not match int, and the last call would not compile.
Map, Filter and Reduce Go Generics Programs
Map, Filter and Reduce are the most asked Go generics programs in interviews. Each one takes a slice and a function.

Program 5: Map a Slice to a New Type
package main
import (
"fmt"
"strings"
)
// Map applies change to every item and returns the new slice.
// T is the input type and Result is the output type, so they can differ.
func Map[T, Result any](items []T, change func(T) Result) []Result {
results := make([]Result, 0, len(items)) // empty slice with room for every item
for _, item := range items {
results = append(results, change(item)) // append adds to the end
}
return results
}
// square returns number times number.
func square(number int) int {
return number * number
}
// label turns a number into a text label like "item-1".
func label(number int) string {
return fmt.Sprint("item-", number)
}
func main() {
numbers := []int{1, 2, 3}
squares := Map(numbers, square)
labels := Map(numbers, label)
upper := Map([]string{"go", "api"}, strings.ToUpper)
fmt.Println(squares)
fmt.Println(labels)
fmt.Println(upper)
}
[1 4 9]
[item-1 item-2 item-3]
[GO API]
Map calls the function you pass on every item and collects the answers. The first call keeps ints, but the second call turns []int into []string. That is why Map needs two type parameters.
Program 6: Filter a Slice
package main
import "fmt"
// Filter keeps only the items where keep returns true.
func Filter[T any](items []T, keep func(T) bool) []T {
var kept []T // starts empty (nil)
for _, item := range items {
if keep(item) {
kept = append(kept, item)
}
}
return kept
}
// isEven reports whether a number divides by 2 with nothing left over.
func isEven(number int) bool {
return number%2 == 0
}
// isLong reports whether a word has more than 2 letters.
func isLong(word string) bool {
return len(word) > 2
}
func main() {
evens := Filter([]int{1, 2, 3, 4, 5, 6}, isEven)
longWords := Filter([]string{"go", "rust", "c", "java"}, isLong)
fmt.Println(evens)
fmt.Println(longWords)
}
[2 4 6]
[rust java]
Filter asks the keep function about each item. If the answer is true, the item goes into the new slice. So the original slice is not changed, and Filter builds a new one.
Program 7: Reduce a Slice to One Value
package main
import "fmt"
// Reduce walks the slice and combines each item into one result.
// start is the first value of the result.
func Reduce[T, Result any](items []T, start Result, combine func(Result, T) Result) Result {
result := start
for _, item := range items {
result = combine(result, item)
}
return result
}
// add returns the running total plus the next number.
func add(total, number int) int {
return total + number
}
// multiply returns the running product times the next number.
func multiply(product, number int) int {
return product * number
}
// addLength returns the running count plus the length of the next word.
func addLength(count int, word string) int {
return count + len(word)
}
func main() {
numbers := []int{1, 2, 3, 4}
total := Reduce(numbers, 0, add)
product := Reduce(numbers, 1, multiply)
letters := Reduce([]string{"go", "is", "fun"}, 0, addLength)
fmt.Println(total, product, letters)
}
10 24 7
Reduce starts with the start value and then folds in each item, one by one. For the total, that is 0+1+2+3+4. The result type can differ from the item type, so in the last call the items are strings but the result is an int.
Program 8: Chain Map, Filter and Reduce
package main
import "fmt"
// Map, Filter and Reduce are the same as in Programs 5 to 7.
func Map[T, Result any](items []T, change func(T) Result) []Result {
results := make([]Result, 0, len(items))
for _, item := range items {
results = append(results, change(item))
}
return results
}
func Filter[T any](items []T, keep func(T) bool) []T {
var kept []T
for _, item := range items {
if keep(item) {
kept = append(kept, item)
}
}
return kept
}
func Reduce[T, Result any](items []T, start Result, combine func(Result, T) Result) Result {
result := start
for _, item := range items {
result = combine(result, item)
}
return result
}
// Order is one item a customer bought.
type Order struct {
Item string
Price int
Paid bool
}
// isPaid reports whether the order was paid.
func isPaid(order Order) bool { return order.Paid }
// getPrice returns the price of the order.
func getPrice(order Order) int { return order.Price }
// add returns the running total plus one price.
func add(total, price int) int { return total + price }
func main() {
orders := []Order{{"pen", 20, true}, {"book", 300, false}, {"bag", 500, true}}
paid := Filter(orders, isPaid) // Step 1: keep paid orders
prices := Map(paid, getPrice) // Step 2: take the price
total := Reduce(prices, 0, add) // Step 3: add them up
fmt.Println("paid total:", total)
}
paid total: 520
This is a real backend task: total the paid orders. First, Filter drops the unpaid book. Then Map turns the two orders into prices, and Reduce adds 20 and 500. Each step is small and easy to test on its own.
Generic Types in Go Generics Programs
Functions are not the only thing that can be generic. A struct can have type parameters too, and many real Go generics programs use generic containers like these.
Program 9: A Simple Generic Box
package main
import "fmt"
// Box holds one value of any type T.
type Box[T any] struct {
Content T
}
func main() {
numberBox := Box[int]{Content: 42} // a Box that holds an int
wordBox := Box[string]{Content: "gift"} // a Box that holds a string
fmt.Println(numberBox.Content + 1) // works because Content is an int
fmt.Println(wordBox.Content + " card") // works because Content is a string
fmt.Printf("%+v\n", numberBox) // %+v prints field names too
}
43
gift card
{Content:42}
Box[T] is a generic type, so you choose T when you create a value. Box[int] holds an int, and Box[string] holds a string. Because Go knows the real type, + 1 and + " card" both compile.
Program 10: A Generic Stack
package main
import "fmt"
// Stack holds items of one type T, last in, first out.
type Stack[T any] struct {
items []T
}
// Push puts an item on top of the stack.
func (stack *Stack[T]) Push(item T) {
stack.items = append(stack.items, item)
}
// Pop returns the top item and true, or the zero value and false.
func (stack *Stack[T]) Pop() (T, bool) {
var zero T // the zero value of T: "" for strings, 0 for ints
if len(stack.items) == 0 {
return zero, false // empty stack: nothing to pop
}
last := len(stack.items) - 1
item := stack.items[last]
stack.items = stack.items[:last] // [:last] keeps everything before the top
return item, true
}
// Len returns how many items are on the stack.
func (stack *Stack[T]) Len() int {
return len(stack.items)
}
func main() {
var letters Stack[string]
letters.Push("a")
letters.Push("b")
letters.Push("c")
for letters.Len() > 0 {
letter, _ := letters.Pop()
fmt.Print(letter, " ")
}
fmt.Println()
_, ok := letters.Pop() // ok is false when nothing was popped
fmt.Println("pop on empty:", ok)
}
c b a
pop on empty: false
Push adds to the end of the slice, and Pop takes from the end, so the last item in is the first out. var zero T gives the zero value of any type: “” for strings, 0 for ints and nil for pointers. This trick appears in almost every generic container.
Program 11: A Generic Set
package main
import (
"fmt"
"slices"
)
// Set uses a map with empty struct values, which take no memory.
type Set[T comparable] map[T]struct{}
// Add puts a value in the set.
func (set Set[T]) Add(value T) {
set[value] = struct{}{} // struct{}{} is an empty value
}
// Has reports whether the value is in the set.
func (set Set[T]) Has(value T) bool {
_, ok := set[value] // ok is true if the key exists
return ok
}
func main() {
tags := Set[string]{}
for _, tag := range []string{"go", "api", "go", "db", "api"} {
tags.Add(tag) // duplicates are ignored by the map
}
fmt.Println(len(tags), tags.Has("db"), tags.Has("java"))
sortedTags := make([]string, 0, len(tags))
for tag := range tags {
sortedTags = append(sortedTags, tag)
}
slices.Sort(sortedTags) // map order is random, so sort before printing
fmt.Println(sortedTags)
}
3 true false
[api db go]
A map can hold each key only once, so adding “go” twice keeps one copy. That is why the set has 3 tags. The key type must be comparable, because map keys are compared with ==.
Program 12: A Generic Pair and Sorted Map Keys
package main
import (
"cmp"
"fmt"
"maps"
"slices"
)
// Pair holds a key and a value of different types.
type Pair[K comparable, V any] struct {
Key K
Value V
}
// SortedPairs turns a map into pairs ordered by key.
func SortedPairs[K cmp.Ordered, V any](table map[K]V) []Pair[K, V] {
var pairs []Pair[K, V]
sortedKeys := slices.Sorted(maps.Keys(table)) // keys in sorted order
for _, key := range sortedKeys {
pairs = append(pairs, Pair[K, V]{Key: key, Value: table[key]})
}
return pairs
}
func main() {
stock := map[string]int{"pen": 40, "bag": 5, "ink": 12}
for _, pair := range SortedPairs(stock) {
fmt.Println(pair.Key, pair.Value)
}
}
bag 5
ink 12
pen 40
First, maps.Keys returns an iterator over the keys, and slices.Sorted collects it into a sorted slice. Then the loop builds one Pair for each key, in that order. So the output is always sorted, even though map order is random.
Most Asked Interview Go Generics Programs
These Go generics programs come up again and again in coding rounds.
Program 13: Reverse Any Slice
package main
import "fmt"
// Reverse swaps items from both ends, moving inwards.
func Reverse[T any](items []T) {
for i := 0; i < len(items)/2; i++ { // only walk to the middle
j := len(items) - 1 - i // the matching position from the end
items[i], items[j] = items[j], items[i] // swap the two items
}
}
func main() {
numbers := []int{1, 2, 3, 4, 5}
names := []string{"asha", "ravi", "meera"}
Reverse(numbers)
Reverse(names)
fmt.Println(numbers, names)
}
[5 4 3 2 1] [meera ravi asha]
The loop swaps the first and last items, then the second and second-last, and so on. It stops at the middle, or it would swap everything back. The swap works in place, so no new slice is created. slices.Reverse in the standard library does the same job.
Program 14: Remove Duplicates and Keep the Order
package main
import "fmt"
// Unique keeps the first copy of each item, in the original order.
func Unique[T comparable](items []T) []T {
seen := make(map[T]bool) // remembers items we already kept
var unique []T
for _, item := range items {
if !seen[item] { // first time we see this item
seen[item] = true
unique = append(unique, item)
}
}
return unique
}
func main() {
fmt.Println(Unique([]int{3, 1, 3, 2, 1}))
fmt.Println(Unique([]string{"b", "a", "b"}))
}
[3 1 2]
[b a]
The map remembers what we have seen, and the slice keeps the order. When an item shows up again, seen is already true, so it is skipped. This runs in one pass, so it is O(n).
Program 15: Min of a Slice with an Error for Empty Input
package main
import (
"cmp"
"errors"
"fmt"
)
// ErrEmpty is the error we return for an empty slice.
var ErrEmpty = errors.New("empty slice")
// MinOf returns the smallest item, or an error if there is none.
func MinOf[T cmp.Ordered](items []T) (T, error) {
var zero T
if len(items) == 0 {
return zero, ErrEmpty // no items: return zero value and an error
}
smallest := items[0]
for _, item := range items[1:] { // [1:] means "from the second item on"
smallest = min(smallest, item) // built-in min works with ordered types
}
return smallest, nil // nil means "no error"
}
func main() {
fmt.Println(MinOf([]int{7, 2, 9}))
fmt.Println(MinOf([]string{"pear", "fig"}))
fmt.Println(MinOf([]float64{}))
}
2 <nil>
fig <nil>
0 empty slice
The function starts with the first item and keeps the smaller one as it walks the rest. For an empty slice, it returns the zero value and ErrEmpty. Returning an error is safer than returning 0, because 0 could also be a real answer.
Generics vs Interfaces in Go Generics Programs
Both features let one piece of code work with many types, but they solve different problems. The table below compares them.
| Feature | Generics | Interfaces |
|---|---|---|
| Type known at | Compile time | Runtime |
| Best for | Containers and slice helpers | Different behaviour per type |
| Example | Stack[T], Map, Filter | io.Reader, Shape with Area() |
| Type checks | Done by the compiler | Type assertions at runtime |
| Return type | The same T you passed | Often the interface type |
A simple rule helps: if the code does the same thing for every type, write Go generics programs. If each type behaves differently, use an interface.
Common Mistakes in Go Generics Programs
- Using any when you need ==:
anydoes not allow==, so usecomparable. - Using comparable when you need <: sorting needs
cmp.Ordered. - Forgetting the ~: a named type like
Rupeeswill not matchintwithout~int. - Generic methods: methods cannot have their own type parameters, only the type can.
- Making everything generic: if only one type is ever used, a normal function is clearer.
Best Practices for Go Generics Programs
- Check the standard library first:
slices,mapsandcmpalready have many helpers. - Use the loosest constraint that works, so more types can use your code.
- Use short names like T, K and V for type parameters.
- Return the zero value with ok or error when there is no result.
- Write generic code after you repeat yourself, not before.
Go Generics Programs Interview Questions and Answers
These are the generics questions interviewers ask most, and they build on the Go generics programs above. Each code answer is complete, with real output from Go 1.27.
Basics Questions
Q1. In which Go version did generics arrive?
Generics arrived in Go 1.18, released in March 2022. Type parameters, constraints and the any and comparable names came with it.
Q2. What is the difference between any and interface{}?
There is no difference. any is an alias for interface{}, added in Go 1.18 to make code shorter to read.
Q3. What does the ~ symbol mean in a constraint?
~int means “int or any type whose underlying type is int”. Without it, only int itself matches.
Q4. Why does this code not compile?
package main
import "fmt"
// Equal tries to compare two values of any type.
func Equal[T any](first, second T) bool {
return first == second // any does not promise that == works
}
func main() {
fmt.Println(Equal(1, 1))
}
incomparable types in type set
Change the constraint to comparable and the code compiles and prints true.
Constraint Questions
Q5. Can a method have its own type parameters?
No. Only the type can have type parameters, like Stack[T]. A method such as func (s *Stack[T]) Map[U any]() is not allowed, so write Map as a normal function instead.
Q6. What is cmp.Ordered?
It is a constraint in the cmp package that includes all integer, float and string types. These are the types that support <, <=, > and >=.
Q7. How do you get the zero value of a type parameter?
Declare var zero T and return it. You can also write *new(T), but var zero T is easier to read.
Q8. What does this program print?
package main
import "fmt"
// Describe returns the name of the real type behind T.
func Describe[T any](value T) string {
return fmt.Sprintf("%T", value) // %T prints the real type of value
}
func main() {
fmt.Println(Describe(42), Describe("hi"), Describe([]bool{true}))
}
int string []bool
Inside a generic function, T is the real type of the call, so %T prints int, string and []bool.
Design Questions on Go Generics Programs
Q9. When should you not use generics?
Do not use generics when each type needs different behaviour. That is a job for interfaces. Also skip them when only one type is used, because a plain function is simpler.
Q10. Are generics slower than normal code?
Usually not by a noticeable amount. Go compiles generic code with a method called GC shape stenciling, which shares code between types of the same shape. For hot paths, measure with a benchmark.
Q11. How do you write a constraint that needs a method?
Put the method in the constraint interface, for example type Stringer interface { String() string }. Then func Join[T Stringer](items []T) can call item.String() on every item.
Q12. What does this program print?
package main
import "fmt"
// Box holds one value of type T.
type Box[T any] struct {
Value T
}
// Get returns the value inside the box.
func (box Box[T]) Get() T {
return box.Value
}
func main() {
numberBox := Box[int]{Value: 5}
wordBox := Box[string]{Value: "go"}
fmt.Println(numberBox.Get()+1, wordBox.Get()+"lang")
}
6 golang
Box[int] and Box[string] are two different types. Get returns the right type each time, so +1 and +"lang" both compile.
Practice Task
To practise Go generics programs, write a generic GroupBy[T any, K comparable](items []T, key func(T) K) map[K][]T function. Use it to group a list of words by their length, then print the groups with the keys in sorted order. Hint: use slices.Sorted(maps.Keys(m)) to sort the keys.
Official Resources
- Tutorial: Getting started with generics
- An Introduction To Generics on the Go blog
- cmp package documentation
Quick Recap
- Go generics programs use type parameters like
[T any]so one function works for many types. comparableallows==, andcmp.Orderedallows<and>.- Map, Filter and Reduce are the most asked generic helpers.
- Generic types like
Stack[T]andSet[T]reuse one design for many types. - Use
var zero Twith an ok flag or error when there is nothing to return.
What’s Next?
Next, we test your Go knowledge with programs that trick most people. Read Go tricky output programs, covering defer, closures, slices and nil interfaces. For more practice, see the Go generics interview questions.


