Skip to content

Generic Data Structures

Build generic data structures that work with any type using Go generics.

Generic data structures like Stack and Queue are perfect use cases for Go generics. Instead of writing separate implementations for IntStack, StringStack, etc., you can write one generic Stack[T] that works with any type.

Key concepts:

  • Zero Values: Use var zero T to get the zero value of a generic type
  • LIFO (Stack): Last-In-First-Out - Push adds to end, Pop removes from end
  • FIFO (Queue): First-In-First-Out - Enqueue adds to end, Dequeue removes from front

Implement three generic data structures:

  1. Stack[T] - Generic stack with Push, Pop, and Peek
  2. Queue[T] - Generic queue with Enqueue and Dequeue
  3. BinarySearch[T] - Generic binary search function

Generic Stack, Queue, and Binary Search

~25 minmedium

Implement generic data structures and algorithms

  • Generic Types: Stack[T any] and Queue[T any] work with any type
  • Zero Values: Use var zero T to get the zero value for type parameter T
  • LIFO vs FIFO: Stack (last in, first out) vs Queue (first in, first out)
  • Boolean Returns: Use (value, bool) pattern to indicate success/failure
  • Generic Algorithms: BinarySearch works with any constraints.Ordered type