Generics
generics
Code Snippets
Bounded Generics with extends
Bounded type parameters and wildcards (`<T extends Number>`, `<? extends Number>`, `<? super Integer>`) are how Java balances type safety with API flexibility. This snippet shows an upper-bounded type parameter for arithmetic, the producer-extends-consumer-super (PECS) rule with wildcards, and a comparator-driven generic max function. Get these right and your collection APIs will accept everything the caller reasonably wants to pass.
Template Constraints with C++20 Concepts (and SFINAE Fallback)
C++20 concepts (`requires` clauses) replace decades of SFINAE incantations with readable predicate-style template constraints. The runnable accordions in this entry use the C++17 `std::enable_if_t` SFINAE form because the test compiler is GCC 9.2 (which lacks concepts), and the C++20 equivalent is shown in inline comments. Reach for concepts on any compiler that supports them; reach for SFINAE only when constrained by toolchain age.
Go Generics with Type Constraints
Go 1.18 added generics; Go 1.21 polished them with the new `cmp` and `slices` packages. This snippet shows a generic `Map`, a numeric constraint via `~int | ~float64`, and a `comparable`-bounded set type. The runnable code targets Go 1.18 syntax (no `cmp.Ordered`, no `slices.Sort`) so it compiles on as many Go versions as possible; the 1.21+ shortcuts are referenced in comments. Note: the project's test runner uses Go 1.13.5 which predates generics, so test execution is expected to FAIL there but the code is valid Go 1.18+.
