Write One Function for Many Types with Go Generics
Go generics let you replace duplicated type-specific functions and unsafe interface{} code with type-safe, reusable algorithms. Learn when to use them and where they cost you.
05 Nov 2026, 10:54 UTC

The problem: the same logic, written twice
Imagine you maintain a service that processes user IDs and product codes. You need a function that removes duplicates from a slice. One version takes []int, another takes []string. Both do exactly the same thing: track seen values in a map and append only new ones. Because Go before version 1.18 had no type parameters, you either duplicated the code or used interface{} (aliased as any) and lost compile-time type safety.
Go 1.18 introduced generics: functions and types parameterized by types. You write the algorithm once, and Go compiles a version for each type you actually use. This post shows how to refactor that duplicated logic, what constraints such as comparable mean, and where generics can hurt build times.
A generic duplicate remover
A type parameter appears in square brackets after the function name. The constraint comparable means values of type T can be used as a map key, which we need for the seen-set.
package main\n\nimport \"fmt\"\n\n// Unique returns a new slice containing the first occurrence of each value.\n// T must be comparable so it can be used as a map key.\nfunc Unique[T comparable](values []T) []T {\n seen := make(map[T]struct{}, len(values))\n result := make([]T, 0, len(values))\n for _, v := range values {\n if _, ok := seen[v]; !ok {\n seen[v] = struct{}{}\n result = append(result, v)\n }\n }\n return result\n}\n\nfunc main() {\n ints := []int{1, 2, 2, 3, 1}\n strings := []string{\"a\", \"b\", \"a\", \"c\"}\n\n // Go infers T from the argument; no need to write Unique[int](ints).\n fmt.Println(Unique(ints)) // [1 2 3]\n fmt.Println(Unique(strings)) // [a b c]\n}\n\n
struct{}{} is an empty struct; it occupies no memory and signals that we only care about map keys, not values. Type inference lets callers write Unique(ints) instead of Unique[int](ints).
When the standard library already has it
Go 1.21 added the slices and maps packages with generic algorithms such as slices.Compact, slices.Sort, and maps.Copy. Before writing your own generic helper, check whether the standard library covers it. For example, deduplicating a sorted slice is one call:
import \"slices\"\n\n// sorted := []int{1, 1, 2, 2, 3}\n// slices.Compact(sorted) // [1 2 3]\n
Generic types, not just functions
Types can be parameterized too. A stack is a classic example:
type Stack[T any] []T\n\nfunc (s *Stack[T]) Push(v T) { *s = append(*s, v) }\nfunc (s *Stack[T]) Pop() (T, bool) {\n if len(*s) == 0 {\n var zero T\n return zero, false\n }\n last := (*s)[len(*s)-1]\n *s = (*s)[:len(*s)-1]\n return last, true\n}\n
any is an alias for interface{} and means \"no constraint\": any type works. Here T is a type parameter, and Stack[int] or Stack[string] are distinct instantiations.
Trade-offs and limits
- \n
- Compile time and binary size. Each distinct type instantiation can generate separate machine code. Overusing generics for many types may slow builds and increase binaries. \n
- Function values. A generic function cannot always be assigned to a variable or passed as an argument without explicitly naming its type arguments, which complicates some reflection-based designs. \n
- Refactoring risk. Replacing
interface{}with generics removes type assertions but changes call sites. Update them one package at a time. \n
Verify your toolchain before you start
Generics require Go 1.18 or later. Run this in your project directory:
$ go version\n
No special permissions are needed. Expected output is a version such as go1.21.0 or newer. If you see an older release, generics will not compile.
Then create a scratch file, for example gen_check.go, and run:
$ go run gen_check.go\n
If the file contains func Identity[T any](t T) T { return t } and calls Identity(42) and Identity(\"hello\"), a successful build confirms type inference works. Editing source files changes repository state, so commit or stash your work first if you are experimenting in a shared branch.
Use generics when repetition outpaces abstraction
Start with the standard library. If you find yourself copying the same loop for []int, []string, and []MyStruct, a generic function with a constraint such as comparable or any is usually the cleaner choice. Measure build times if you instantiate the same generic type with dozens of unrelated types.