Skip to content
FutureBlitz

    Install

    Learn

    Generics

    Write functions and types once, with type parameters, and use them with any type that fits.

    Generics let one function or type work with many types. A type parameter, like the T in Stack<T>, stands for a type that each use supplies, and a constraint says what that type must be able to do. The compiler builds a separate copy for each set of types a program uses, so generic code runs as fast as code written for one type. std’s collections, sorting, and serialization are built this way, and these tutorials show how to write your own.

    Tutorials

    1. Generic functions Write a function once, with type parameters, and call it with arrays of any type.
    2. Generic types Classes, Structs, and Interfaces with type parameters, and Methods with type parameters of their own.
    3. Constraints Say what a type parameter must be able to do, with inline constraints, Where lines, and Interfaces of your own.
    4. Inference and defaults How the compiler works out type arguments, when you write some of them, and how generic code makes a value of T from nothing.

    The rules behind this area are in the language reference.

    Report an issue with this page or with FutureBlitz on GitHub.