Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 132 ยท Generics

Generics

Learn Rust generics: generic functions, structs, enums and impl blocks, monomorphization, the turbofish, default parameters and generics vs trait objects.

Suppose you write a function that returns the larger of two i32 values. A week later you need the same thing for f64, then for char, then for your own Version type. Copying the function four times is a maintenance trap: a bug fixed in one copy lives on in the others. Generics solve this. You write the code once, with a placeholder for the type, and the compiler produces a specialised version for each real type you use.

You have already used generics every day. Vec<i32>, Option<String>, Result<u8, ParseIntError> and Box<dyn Error> all take type parameters, and Option was an enum with a <T> in its definition. This lesson shows how to write your own generic functions, structs, enums and methods, explains why Rust's generics cost nothing at run time, and ends with the choice between generics and trait objects. The next lesson, Trait bounds, explains how to say what a placeholder type must be able to do.

A generic function

A type parameter is written in angle brackets after the function name. By convention a single parameter is called T (for "type"). The parameter can then be used anywhere a type could appear.

Rust
fn first_or<T>(items: &[T], fallback: T) -> T

Start with something that needs no capabilities from T at all: swapping the two halves of a pair.

Rust Your first generic function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

swap_pair has two parameters, A and B, because the two halves can be different types. The compiler works out A and B from the arguments, which is called type inference. For the last call there are no elements to infer from, so the code spells the type out with ::<char>.

The turbofish

The ::<...> syntax is nicknamed the turbofish. You need it whenever the compiler cannot infer a type parameter and there is no place to put a let annotation. The two most common cases are parse and collect.

Rust The turbofish in practice

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Both forms mean the same. Prefer the annotation on the variable when you have a let; use the turbofish in the middle of a chain.

Generic structs

A struct can declare type parameters after its name, and then use them in its fields. The impl block must declare the parameter again, because impl<T> says "for every T" and Point<T> says which type we are implementing for.

Rust A generic struct with methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Two things are worth noticing. First, Point::new(3, 4) infers T = i32 and Point::new(3.0, 4.0) infers T = f64; they are different types that happen to share a recipe. Second, impl Point<f64> is a block that exists only for Point<f64>. int_point.distance_from_origin() would not compile, because that method does not exist for Point<i32>. This is how you offer a method to only some instantiations of a generic type.

If both fields must be allowed to differ, give them separate parameters.

Rust Two type parameters and mixing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The method brings its own parameters C and D in addition to the ones from the impl. That is legal and useful when a method returns a different instantiation of the same type, as Option::map does.

Generic enums

You have seen the two most famous generic enums. Their real definitions are tiny.

Rust
enum Option<T> {
    None,
    Some(T),
}

enum Result<T, E> {
    Ok(T),
    Err(E),
}

Your own enums can do the same. This one models a value that is either on its way or has arrived.

Rust A generic enum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Notice that Delivery::Pending still needs a T to be known: a bare Delivery::Pending could be a Delivery<u32> or a Delivery<&str>, so the examples annotate the variable. Enums and pattern matching covers the variants themselves.

Monomorphization: generics cost nothing

When you compile swap_pair((1, "one")) and swap_pair(("pi", 3.14)), the compiler does not keep one slow, flexible function that checks types at run time. It creates two separate functions, one for (i32, &str) and one for (&str, f64), as if you had written both by hand. This process is called monomorphization ("making single-shaped"). The consequences are the main selling point of Rust's generics:

  • No run-time overhead. Calls are direct and can be inlined. A generic max over integers compiles to the same machine code as a hand-written max_i32.
  • No boxing. A Vec<u8> stores plain bytes, not pointers to objects.
  • Larger binaries are possible. Each instantiation is separate code. If you use a big generic function with fifty different types, you get fifty copies. This is called code bloat and is usually minor, but it is one reason compile times grow with heavy generic use.

You can watch it happen. std::any::type_name reports the concrete type the compiler chose for each instantiation, and size_of shows that the layouts differ.

Rust Each instantiation is its own type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Each call to describe runs in a function compiled just for that type. A Wrapper<u16> takes two bytes, because the struct has no overhead of its own.

There is no "generic type" at run time in Rust, unlike Java, where type arguments are erased and everything becomes an object reference. In Rust the types are fully known at compile time, so you cannot ask a T "what are you?" while the program runs, except through special traits such as Any.

Default type parameters

A type parameter may have a default, written T = Default. Callers who do not care can omit it. The standard library uses this heavily, for example HashMap<K, V, S = RandomState> and Add<Rhs = Self>.

Rust A default type parameter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Defaults apply only in type positions. When you write Meters(2.5) without an annotation, inference decides T; the default is not consulted.

What a bare T cannot do

A bare T knows nothing. You cannot add two T, compare them, print them or copy them, because not every type supports those operations. This is the most common error learners meet with generics, and it is what trait bounds fix.

Rust Comparing two unknown types (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The compiler stops at the comparison with error[E0369]: binary operation \>` cannot be applied to type `&T``, and the help text suggests restricting the type parameter with T: std::cmp::PartialOrd. That fix is the subject of the next lesson. Rust deliberately checks generic code once, when it is defined, not at each call site as C++ templates do. The upside is clear error messages at the definition and a guarantee that a generic function that compiles will work for every type that satisfies its bounds.

Generics or trait objects?

Rust offers two ways to write code that works with many types.

Generics (T: Trait) Trait objects (dyn Trait)
Dispatch Static: resolved at compile time Dynamic: through a vtable at run time
Speed Inlinable, zero overhead One indirect call per method
Binary size One copy per type One copy
Mixed collection No: every element is the same type Yes: Vec<Box<dyn Shape>>
Type known at compile time Required Not required

Use generics by default: they are faster and give better type checking. Reach for dyn Trait when you truly need a collection of different concrete types, plugin-style extension, or want to keep compile times and binary size down. Trait objects shows the dynamic side in detail. The same question returns in the advanced traits lesson as impl Trait versus dyn Trait.

When to use and when to avoid

Make a function or type generic when two or more real types need the same logic, such as a container, a numeric helper or an algorithm over any iterator. Do not make it generic "just in case". A function taking &str is simpler to read and call than fn f<S: AsRef<str>>(s: S), and each generic parameter you add multiplies the possible instantiations a reader must hold in mind. Start concrete, and generalise when a second use appears.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the compiler do with a generic function when you call it with i32 and with f64?

    Rust monomorphizes generics: each concrete type gets its own compiled copy, so there is no run-time type check and no boxing.
  2. 2. When do you need the turbofish ::<T>?

    The turbofish supplies a type parameter explicitly. It is needed when inference has nothing to go on, for example "42".parse::<u64>().
  3. 3. What does impl Point<f64> { ... } mean?

    An impl block for a concrete instantiation adds methods to that instantiation only, such as a distance method that needs floating-point numbers.
  4. 4. Why does fn largest<T>(items: &[T]) -> &T fail when it uses >?

    An unconstrained T can be any type, including ones that cannot be ordered. You must add a bound such as T: PartialOrd.
  5. 5. Which statement about the run-time cost of generics is true?

    Because each instantiation is compiled separately and calls are direct, generics have zero abstraction cost. The price is possibly larger binaries.

Summary

  • Generics let one definition work for many types: fn f<T>(...), struct S<T>, enum E<T>, impl<T> S<T>.
  • Inference usually fills in the parameters; the turbofish ::<Type> supplies them when it cannot.
  • An impl for a concrete instantiation, like impl Point<f64>, adds methods to only that case.
  • Monomorphization compiles one specialised copy per type, so generics are fast and need no boxing; the cost is possible code bloat.
  • A bare T supports no operations; trait bounds say what it can do.
  • Prefer generics for static dispatch; use dyn Trait for mixed collections, and keep code concrete until a second use appears.

Next: Trait Bounds and where Clauses