Stage 1 · Code
Generics
Generic Types
See how generics apply to structs and methods, then build a reusable stack that works with any element type while still feeling like normal Go.
Why Make a Type Generic
Think about a shelf organizer with adjustable dividers. The organizer's shape stays the same whether you fill it with screws, postcards, or tea bags. You do not build a brand new organizer for every item category. You build one organizer that can hold different kinds of things.
A generic type is the same idea in code. Sometimes the structure itself is reusable. A stack is still a stack whether it stores int, string, or Task. The behavior is stable. Only the element type changes.
Building a Generic Stack
A stack follows one simple rule: last in, first out. The most recently pushed item is the first one you pop back out. That is useful for undo history, expression evaluation, backtracking, and many other jobs.
The stack's logic never asked whether it was holding numbers, strings, or structs. It only needed a slice and the push-pop rules. That is exactly the kind of stable structure generics fit well.
Methods on Generic Types
Methods on a generic type repeat the type parameter in the receiver. Read func (s *Stack[T]) Push(value T) as: 'this is a method on a pointer to a Stack whose element type is the same T used by the stack itself.'
type Stack[T any] structdefines a type that needs one type argument before it becomes fully concrete.Stack[int]andStack[string]are different concrete instantiations of that type.- A method like
Pushuses the receiver*Stack[T], so the method works with the same element type the stack was created for. - The method does not invent a new unrelated type parameter. It uses the stack's existing one.
Once you have a Stack[string], every method call on that value is a string stack operation. You do not re-choose the element type for each method call.
Another Small Example
Not every generic type needs complex behavior. Sometimes the type itself is just a reusable container for pairing two related values.
Tracing Stack Operations
Now let's trace a stack with real values and watch its internal slice change after each operation.
Quiz
When is a generic type a good fit?
Practice
Finish a small generic type: write the `Get` method for `Box[T]` so it returns the stored value.
Summary
- Generic types are useful when the container or structure is reusable across many element types.
- A type like
Stack[T]becomes concrete only when you supply a real type argument such asintorstring. - Methods on generic types repeat the type parameter in the receiver, such as
*Stack[T]. - Once you create
Stack[string], all its methods work with strings for that specific value. - Tracing the internal slice makes it clear that generic types still behave like ordinary concrete types at runtime.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.