Generic Data Structures
Generic Data Structures
Section titled “Generic Data Structures”Build generic data structures that work with any type using Go generics.
Background
Section titled “Background”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 Tto get the zero value of a generic type - LIFO (Stack): Last-In-First-Out -
Pushadds to end,Popremoves from end - FIFO (Queue): First-In-First-Out -
Enqueueadds to end,Dequeueremoves from front
Your Task
Section titled “Your Task”Implement three generic data structures:
Stack[T]- Generic stack with Push, Pop, and PeekQueue[T]- Generic queue with Enqueue and DequeueBinarySearch[T]- Generic binary search function
Generic Stack, Queue, and Binary Search
~25 minmedium
Implement generic data structures and algorithms
Key Concepts
Section titled “Key Concepts”- Generic Types:
Stack[T any]andQueue[T any]work with any type - Zero Values: Use
var zero Tto 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.Orderedtype