Skip to content
Latchkey

What Is a Generic? Code That Works Across Types

A generic is code parameterized by type: a function or data structure written once that works with many types while keeping full type safety.

Without generics, you either write the same logic over and over for each type, or you throw away type safety by using a catch-all type. Generics solve this by letting you write a function or container with a type placeholder, filled in when used. A generic list can hold strings or numbers, and the compiler still checks each use correctly.

What generics give you

Generics let one definition serve many types without duplication or loss of safety. A generic List<T> is a list of whatever T you supply, and the compiler enforces that a list of numbers only ever holds numbers, even though the code was written abstractly.

Why generics matter

  • Reuse: write an algorithm or container once for all types.
  • Type safety: no casting and no runtime type errors from misuse.
  • Clear intent: signatures express relationships between types.
  • Better tooling: autocomplete and checks follow the concrete type.

Generics vs the alternatives

The alternatives are duplicating code per type (tedious and error-prone) or using an opaque any/object type (which discards checking). Generics give the reuse of the latter with the safety of the former.

How generics are implemented

Languages differ. Some specialize generic code for each concrete type at compile time (monomorphization, as in Rust and C++), which is fast but grows the binary. Others erase types and share one implementation (type erasure, as in Java). The trade is speed versus code size.

A quick example

A generic function first<T>(items: T[]): T returns the first element of an array of any type T, and the compiler knows the result is a T, preserving type information end to end.

Generics in CI

Heavy generic code, especially monomorphized generics, can make compilation slower and more memory-hungry, since the compiler generates a version per concrete type. Larger runners (Latchkey) shorten these builds, and transient OOM or toolchain blips during compilation can be auto-retried.

Key takeaways

  • A generic is type-parameterized code that works with many types while staying type-safe.
  • Generics give reuse without sacrificing the safety a type system provides.
  • Implementation strategies trade runtime speed against binary size and build time.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →