Generics

Generics is the topic of generalizing types and functionalities to broader
cases. This is extremely useful for reducing code duplication in many ways,
but can call for rather involving syntax. Namely, being generic requires
taking great care to specify over which types a generic type
is actually considered valid. The simplest and most common use of generics
is for type parameters.

A type parameter is specified as generic by the use of angle brackets and upper
camel case: <Aaa, Bbb, ...>. “Generic type parameters” are
typically represented as <T>. In Rust, “generic” also describes anything that
accepts one or more generic type parameters <T>. Any type specified as a
generic type parameter is generic, and everything else is concrete (non-generic).

For example, defining a generic function named foo that takes an argument
T of any type:

  1. fn foo<T>(arg: T) { ... }

Because T has been specified as a generic type parameter using <T>, it
is considered generic when used here as (arg: T). This is the case even if T
has previously been defined as a struct.

This example shows some of the syntax in action:

  1. // A concrete type `A`.
  2. struct A;
  3. // In defining the type `Single`, the first use of `A` is not preceded by `<A>`.
  4. // Therefore, `Single` is a concrete type, and `A` is defined as above.
  5. struct Single(A);
  6. // ^ Here is `Single`s first use of the type `A`.
  7. // Here, `<T>` precedes the first use of `T`, so `SingleGen` is a generic type.
  8. // Because the type parameter `T` is generic, it could be anything, including
  9. // the concrete type `A` defined at the top.
  10. struct SingleGen<T>(T);
  11. fn main() {
  12. // `Single` is concrete and explicitly takes `A`.
  13. let _s = Single(A);
  14. // Create a variable `_char` of type `SingleGen<char>`
  15. // and give it the value `SingleGen('a')`.
  16. // Here, `SingleGen` has a type parameter explicitly specified.
  17. let _char: SingleGen<char> = SingleGen('a');
  18. // `SingleGen` can also have a type parameter implicitly specified:
  19. let _t = SingleGen(A); // Uses `A` defined at the top.
  20. let _i32 = SingleGen(6); // Uses `i32`.
  21. let _char = SingleGen('a'); // Uses `char`.
  22. }

See also:

structs