Skip to content
Tutorials Center
My learning

Topics

Lesson 57 of 147 ยท Generics

Generic Types and Methods

Learn Go generic types - generic structs like Stack[T] and Cache[K, V], methods on generic types, constructors, zero values of T, generic type aliases from Go 1.24 and the generic methods added in Go 1.27.

Generic functions are only half of the story. The other half is generic types: structs, slices, maps and other types that carry type parameters. A stack of ints, a stack of strings and a stack of users should all be one Stack[T], not three copies. The standard library is full of them: atomic.Pointer[T], sync.OnceValue, iter.Seq[V], list-like containers in your own projects and most data structures you will write.

This lesson shows how to declare a generic type, write methods for it, create values with constructors, deal with the zero value of T, build useful containers (stack, set, cache, linked list), use generic type aliases (Go 1.24), and see how Go 1.27 finally lets methods declare type parameters of their own. You should already know generic functions and constraints.

Declaring a generic type

A type declaration gets type parameters in square brackets, just like a function. The parameters can then be used inside the type:

Go A generic pair and a generic slice type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

When you use a generic type you normally instantiate it by supplying type arguments: Pair[string, int]. Unlike generic functions, a generic type usually cannot infer its arguments from a composite literal, so you write them out (a constructor function, shown below, can hide that). Each instantiation is its own type: Pair[string, int] and Pair[int, string] are different types, and %T prints the arguments.

Inside the declaration a type can refer to itself with its own parameters, as Node[T] does for its children.

Methods on generic types

To add methods, write the type parameters in the receiver, in square brackets after the type name. The names are yours to choose, and you do not repeat the constraint:

Go A generic Stack with methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Three details deserve attention:

  1. The receiver is (s *Stack[T]). T here is a fresh name bound to the type's parameter. You could call it E in a method, though consistency helps readers.
  2. The zero value is useful. var ints Stack[int] works without a constructor because a nil slice is a valid empty slice. Designing for a useful zero value is idiomatic Go (see Constructors, Options and Builders).
  3. var zero T is the way to return "nothing" of an unknown type. We return (T, bool) rather than a pointer or a panic, mirroring the map lookup style v, ok := m[k].

Setting s.items[last] = zero is a small but important habit when T may hold pointers: it clears the vacated slot so the slice's backing array does not keep the object alive.

Constructors

A generic function that returns a generic type is the idiomatic constructor, and it brings back type inference:

Go Constructors and a Set built on a map

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

NewSet(3, 1, 2, 3, 3) infers T = int, so callers never type Set[int] themselves. Notice the function SortedValues: the methods of a generic type share exactly the constraints of the type. A method cannot say "only when T is ordered". If you need more than the type promises, write a top-level function with a stricter constraint, as SortedValues does.

Methods with their own type parameters (Go 1.27)

For years the biggest restriction in Go generics was that a method could use the type parameters of its receiver but could not declare new ones. Wanting Map as a method of Box[T] meant giving up the dot syntax. Go 1.27 lifts that restriction: a method may now have its own type parameters after its name.

Go A method with its own type parameter (Go 1.27)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The call b.Map(f) reads naturally and chains. The receiver's T comes from the type of b, and U is inferred from the function argument exactly like for a generic function; you can also supply it explicitly, as in b.Map[float64](...).

The new freedom has two limits you should know:

  • A generic method cannot be part of an interface. An interface method cannot declare type parameters, and a type's generic method does not count when checking whether the type implements an interface.
  • The receiver keeps the constraints of its type. A method cannot say "only when T is ordered". Introduce stricter constraints with a plain function instead.
Go Generic methods and interfaces (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The compiler rejects the assignment: Plain does not implement Converter (wrong type for method Conv), printing have Conv[U any](U) string and want Conv(int) string. A generic method is a different thing from a method with concrete parameter types, so write a normal method (or a wrapper) when you need to satisfy an interface. Declaring the interface itself as Conv[U any](u U) string is an error too: interface method must have no type parameters.

Using a function instead

Generic functions remain the portable choice: they work in every Go version since 1.18 and have no interface caveats. The same Map as a function:

Go A generic function instead of a generic method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The call reads MapBox(b, f) instead of b.Map(f), and chaining nests, but the result is identical. Libraries that support older Go versions still use this form, and slices and maps use functions rather than methods by design.

A generic cache with two type parameters

Generic types often take several parameters. A cache maps keys of type K to values of type V; the key must be comparable because it is used in a map:

Go A small Cache[K, V] with a fixed capacity

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Here NewCache has no arguments that mention K or V, so the caller must write NewCache[string, int](2). This is the same limitation as Zero[T]() from the previous lessons. The output shows evicted: b a second time because GetOrCompute stored a third key in a full cache. Caches shared between goroutines also need a mutex, which you can add as a field without touching the type parameters.

A generic linked list and iteration

Self-referential generic types work too. Since Go 1.23 a generic container can offer a range-over-function iterator by returning an iter.Seq[T] (covered in Iterators):

Go A linked list that works with range

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The type element[T] is unexported, which is a good habit: callers should only see the list, not the plumbing. Because All returns iter.Seq[T], for w := range list.All() just works, and so does slices.Collect(list.All()).

Generic type aliases (Go 1.24)

A regular type alias (type X = Y) gives another name to an existing type. Before Go 1.24 an alias could not have type parameters. Since 1.24 you can declare a generic alias:

Go Generic type aliases

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Because an alias is the same type as its target, %T shows map[int]struct {} and main.Pair[string,float64]. Generic aliases are mainly for refactoring and for giving shorter names to partially applied generic types. Use a defined type (type Set[T comparable] struct{...}) when you want your own methods.

Embedding and zero values

Generic structs can embed other generic types, and the zero value rules are unchanged: every field has its zero value. A few practical notes:

  • A generic type's zero value is only useful if its fields have useful zero values. A Set with a map field is not usable at the zero value (writing to a nil map panics), which is why NewSet exists. Document or provide a constructor.
  • var zero T is the only portable "empty T". Using *new(T) is equivalent.
  • Comparing generic values with == requires comparable; copying a struct that holds a mutex is a bug (run go vet) whatever its type arguments are.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How do you write the receiver of a method Push on type Stack[T any] struct{ items []T }?

    The receiver repeats the type parameter names in square brackets, without constraints: (s *Stack[T]).
  2. 2. Which of these is a compile error in Go 1.27?

    Since Go 1.27 a concrete type may have methods with their own type parameters, but an interface method must have no type parameters.
  3. 3. Why must Cache[K comparable, V any] constrain K with comparable?

    Map keys must support ==, so the type parameter used as the key needs the comparable constraint.
  4. 4. What does var zero T give you inside a generic method?

    var zero T produces 0 for numbers, "" for strings, nil for pointers and so on, depending on the type argument.
  5. 5. What is true of type Set[T comparable] = map[T]struct{} (Go 1.24)?

    An alias is another name for the same type. Go 1.24 allows aliases to have type parameters.

Summary

  • Declare generic types with type parameters: type Stack[T any] struct{ ... }; instantiate them as Stack[int].
  • Methods repeat the parameters in the receiver, func (s *Stack[T]) Push(v T), and share the type's constraints. Since Go 1.27 a method may also declare its own type parameters (func (b Box[T]) Map[U any](...)), but such a method cannot satisfy or appear in an interface.
  • Use a generic function when you need extra type parameters or a stricter constraint.
  • Constructors like NewSet(values...) let the compiler infer type arguments; with none to infer from, callers write NewCache[string, int](2).
  • var zero T is the zero value of the type parameter; clear vacated slots in containers to avoid keeping objects alive.
  • Generic containers can return iter.Seq[T] so callers can use range.
  • Go 1.24 allows generic type aliases such as type Set[T comparable] = map[T]struct{}.

Next: Generics in Practice: When to Use Them helps you decide when generics are worth it.