Skip to content

Generics Exercises

Practice using Go’s generics with type parameters, constraints, and generic data structures.

ExerciseDifficultyTimeDescription
Generic FunctionsEasy15 minWrite generic utility functions
Generic Data StructuresMedium25 minImplement a generic stack and queue
  • Type parameters: Defining generic types and functions
  • Constraints: Restricting type parameters
  • Built-in constraints: any, comparable
  • Custom constraints: Creating interface constraints
  • Type inference: When Go can infer type arguments

Before starting these exercises, you should be comfortable with:

  • Go interfaces
  • Structs and methods
  • Chapter 13: Generics
  1. Only use generics when you need them - simple functions are clearer
  2. Prefer constraints over any when possible
  3. Consider if an interface would work just as well