Module 10 · Lesson 3 of 548/50 in the course~15 min
Module lessons (3/5)
Generics (Go 1.18+)
Lesson preview5 hands-on exercises readyCourse Go · Module 10 — Idiomatic practice
Type parameter func Map[T, U any](s []T, f func(T) U) []U, constraints (comparable, custom), trade-off.
What you'll learn in this lesson
- Declare generic functions with type parameter (
[T, U any]) using compiler inference. - Distinguish the built-in constraints
any(no operator) andcomparable(equality==/!=). - Construct ad hoc constraints with type unions (
~int | ~string) and learn aboutcmp.Ordered. - Parameterize
structand methods respecting Go's constraints on generic methods.
Overview
Introduced in Go 1.18, type parameters (generics) allow you to write reusable algorithms and strongly typed containers without duplication or loss of type-safety via any and type assertion at runtime.
The list of type parameters appears in square brackets [...] immediately after the function name:
Sections covered in this lesson
- 1Generic functions and type inference
- 2Constraint
any,comparableand union types - 3Generic structures and methods
- 4Guided practice
- 5Check for understanding
Pro Lesson · Module 10 — Idiomatic practice
Unlock "Generics (Go 1.18+)" and the full Course Go curriculum
Type parameter `func Map[T, U any](s []T, f func(T) U) []U`, constraints (`comparable`, custom), trade-off.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Course Go plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.