Skip to content

Generic Functions

Learn to write generic functions that work with multiple types using Go’s generics feature introduced in Go 1.18.

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 <, <=, >, >=.

Implement four generic utility functions:

  1. Min - Returns the smaller of two values (works with any ordered type)
  2. Map - Transforms a slice by applying a function to each element
  3. Filter - Returns elements that satisfy a predicate function
  4. Contains - Checks if a slice contains a specific value

Generic Utility Functions

~15 mineasy

Implement Min, Map, Filter, and Contains using generics

  • Type Parameters: Define generic functions with [T any] or [T SomeConstraint]
  • Constraint Interfaces: Use comparable for equality checks, constraints.Ordered for 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