Generics

Generics are a concept to refer to many types at once, and to be polymorphic over them. Generics use the angle bracket syntax, which is common in many C-like languages.

An identifier that refers to many types is called a type parameter, a type variable or simply a generic type. A type, trait, function or  block with a type parameter is called generic. Strictly speaking, types, traits, functions and  blocks with a lifetime are also generic. For functions, this isn't always visible, since lifetimes are often elided.

Example
This example illustrates where generics can be used. The identifier  is used as type parameter, which is common practice in Rust. Each type parameter must be declared before it can be used:

Bounds
Type parameters and lifetimes can be bounded by traits and by lifetimes. Bounds appear after a colon after the parameter and are separated with a   sign. It is possible to move bounds to a  clause:

Lifetimes on generics
Each type parameter has an implicit lifetime bound, since it can potentially be used for a type which borrows data. This can be prevented by adding an explicit bound, which means that the type must not borrow values, unless these borrows have the  lifetime: When omitting the lifetime, it is usually inferred correctly, so this doesn't need to be considered except in rare edge cases.

Usage
When using a generic trait or type, its type parameters must be substituted with concrete types or with new type parameters.

To substitute a generic parameter on a type or trait, wrap the list of parameters in less than / greater than signs:. To make the compiler infer it, write an underscore in place of the parameter:, though this is only allowed in type ascriptions in a function body, since type inference is not allowed elsewhere:

In generic function calls and other generics in a value context, the syntax is different:


 * Omitting the list of generic parameters entirely is allowed, if enough information exists inside the function to infer the types
 * The list of generics has to be written as the so-called turbofish, which two colons before the less-than sign: