Functions

The same set of rules can be applied to functions: a type T becomes
generic when preceded by <T>.

Using generic functions sometimes requires explicitly specifying type
parameters. This may be the case if the function is called where the return type
is generic, or if the compiler doesn’t have enough information to infer
the necessary type parameters.

A function call with explicitly specified type parameters looks like:
fun::<A, B, ...>().

  1. struct A; // Concrete type `A`.
  2. struct S(A); // Concrete type `S`.
  3. struct SGen<T>(T); // Generic type `SGen`.
  4. // The following functions all take ownership of the variable passed into
  5. // them and immediately go out of scope, freeing the variable.
  6. // Define a function `reg_fn` that takes an argument `_s` of type `S`.
  7. // This has no `<T>` so this is not a generic function.
  8. fn reg_fn(_s: S) {}
  9. // Define a function `gen_spec_t` that takes an argument `_s` of type `SGen<T>`.
  10. // It has been explicitly given the type parameter `A`, but because `A` has not
  11. // been specified as a generic type parameter for `gen_spec_t`, it is not generic.
  12. fn gen_spec_t(_s: SGen<A>) {}
  13. // Define a function `gen_spec_i32` that takes an argument `_s` of type `SGen<i32>`.
  14. // It has been explicitly given the type parameter `i32`, which is a specific type.
  15. // Because `i32` is not a generic type, this function is also not generic.
  16. fn gen_spec_i32(_s: SGen<i32>) {}
  17. // Define a function `generic` that takes an argument `_s` of type `SGen<T>`.
  18. // Because `SGen<T>` is preceded by `<T>`, this function is generic over `T`.
  19. fn generic<T>(_s: SGen<T>) {}
  20. fn main() {
  21. // Using the non-generic functions
  22. reg_fn(S(A)); // Concrete type.
  23. gen_spec_t(SGen(A)); // Implicitly specified type parameter `A`.
  24. gen_spec_i32(SGen(6)); // Implicitly specified type parameter `i32`.
  25. // Explicitly specified type parameter `char` to `generic()`.
  26. generic::<char>(SGen('a'));
  27. // Implicitly specified type parameter `char` to `generic()`.
  28. generic(SGen('c'));
  29. }

See also:

functions and structs