Generic Functions
Generic Functions
Section titled “Generic Functions”Learn to write generic functions that work with multiple types using Go’s generics feature introduced in Go 1.18.
Background
Section titled “Background”Go generics allow you to write functions that work with any type, not just a specific one. This is useful for creating reusable utility functions like Min, Map, Filter, and Contains that work with integers, strings, floats, and other types.
Type parameters are defined in square brackets [T any] before the function parameters. The any constraint means the type can be anything, while comparable means types that support == and !=, and constraints.Ordered means types that support <, <=, >, >=.
Your Task
Section titled “Your Task”Implement four generic utility functions:
Min- Returns the smaller of two values (works with any ordered type)Map- Transforms a slice by applying a function to each elementFilter- Returns elements that satisfy a predicate functionContains- Checks if a slice contains a specific value
Generic Utility Functions
~15 mineasy
Implement Min, Map, Filter, and Contains using generics
Key Concepts
Section titled “Key Concepts”- Type Parameters: Define generic functions with
[T any]or[T SomeConstraint] - Constraint Interfaces: Use
comparablefor equality checks,constraints.Orderedfor comparisons - Type Inference: Go can often infer type parameters from function arguments
- Multiple Type Parameters: Functions like Map use
[T, U any]for input and output types - Generic Patterns: Common functional programming patterns (map, filter, contains) work across all types