Skip to content
Theory · Generics and traits · lesson 1 of 8

Generic functions and types

What you'll learn

What you'll learn:

  • write one function and one struct for many types at once;
  • explain why a T with no bound can do nothing, and add the bound T: PartialOrd;
  • describe the shared behavior of different types with a trait and give its methods a default body;
  • print your own types with {} and explain what the compiler turns a generic function into.
A star cookie cutter T hangs above two sheets of dough, i32 and char, and the same star is cut out of each

Picture a star-shaped cookie cutter. With one cutter you can stamp a star out of shortbread dough, chocolate dough or gingerbread dough. The cutter sets the outline, and a fresh dough goes under it each time.

Programs work the same way: one action, different data types. Take a function that picks the larger of two values. For i32 and for char you have to write it twice:

Rust
fn largest_i32(a: i32, b: i32) -> i32 {
    if a > b { a } else { b }
}

fn largest_char(a: char, b: char) -> char {
    if a > b { a } else { b }
}

fn main() {
    println!("{}", largest_i32(7, 3)); // 7
    println!("{}", largest_char('a', 'z')); // z
}

Let's compare the two functions:

  1. The bodies match word for word: if a > b { a } else { b }.
  2. Only the types in the header differ: i32 in the first and char in the second.
  3. f64 would need a third copy, u8 a fourth.

Copies are bad for more than their length. Find a bug in one, and you have to hunt it down and fix it in all of them. What you need is a cutter: one body, with the type filled in later.

A generic function

A generic function is a function with a type parameter in place of a concrete type. It is usually called T. Let's rewrite largest once for every type:

Rust
fn largest<T: PartialOrd>(a: T, b: T) -> T {
    if a > b { a } else { b }
}

fn main() {
    println!("{}", largest(7, 3)); // 7
    println!("{}", largest('a', 'z')); // z
    println!("{}", largest(1.5, 2.5)); // 2.5
}

Let's take the header fn largest<T: PartialOrd>(a: T, b: T) -> T apart:

  • <T: PartialOrd> right after the name declares the type parameter T;
  • : PartialOrd requires values of type T to be comparable with > and <;
  • (a: T, b: T) — both arguments have the same type T;
  • -> T — the result has that type too.

The call picks T, not the function. In largest(7, 3) the compiler sees two i32 values and fills in T = i32; in largest('a', 'z') it is T = char; in largest(1.5, 2.5) it is T = f64. You don't write the type at the call: the compiler infers it from the arguments, the way it infers a type in let.

A bound

This is where the cookie cutter picture ends. A cutter stamps a star out of any dough, but a generic function does not work with every type. The body of largest compares a > b, and not every type can be compared: Rust cannot compare two Point structs.

So Rust checks the body of a generic function once, for any T at all, not separately for each call. The compiler knows only what the header promises about T.

A bound is a clause like T: PartialOrd: it promises that type T can do what the trait PartialOrd requires, which is comparison. With that promise, a > b is allowed in the body. In return, largest can be called only with types that can be compared.

PartialOrd is a trait, like the Debug you already know: an ability some types have and others don't. Without a bound, T promises nothing. You can pass such a value on or return it, but you cannot compare it, add it or print it.

Generic types

A struct can have a type parameter too. A generic type is a struct or enum with a type parameter: one cutter for data of many types. You have used such types already: Vec<T> holds elements of any type, and Option<T> holds any value or nothing.

Rust
struct Point<T> {
    x: T,
    y: T,
}

impl<T> Point<T> {
    fn x(&self) -> &T {
        &self.x
    }
}

fn main() {
    let p = Point { x: 1.5, y: 0.5 };
    println!("{} {}", p.x(), p.y); // 1.5 0.5
}

Let's go through the example line by line:

  1. struct Point<T> declares a point with a type parameter, and both fields x and y have type T.
  2. impl<T> Point<T> holds methods for a point with any T. The first <T>, after impl, declares the parameter; the second says which type the methods belong to.
  3. The method x returns a reference &T to the field. You cannot take the field out of &self: T may turn out to be a String rather than a Copy type, so the method lends the value.
  4. Point { x: 1.5, y: 0.5 } is a Point<f64>, and Point { x: 1, y: 2 } would be a Point<i32>. Here, too, the compiler infers the type.
  5. The program prints 1.5 0.5.

Inside one point, T is one type: both fields are i32, or both are f64. If you forget the <T> after impl and write impl Point<T>, the compiler cannot find the type T (error E0425) and suggests adding impl<T>.

Common mistake

The bound is left out, since i32 can be compared anyway:

Rust
fn largest<T>(a: T, b: T) -> T {
    if a > b { a } else { b } // ✗
}

fn main() {
    println!("{}", largest(7, 3));
}
TEXT
error[E0369]: binary operation `>` cannot be applied to type `T`

The program does not compile, even though the call passes ordinary i32 values. Rust does not wait for T = i32: it checks the body once, against the header's promises alone, and a T with no bound promised nothing. This is a build error, not a panic, and the compiler suggests the fix itself: T: PartialOrd.

Interviewers like to ask this, especially of people who know C++. A C++ template is checked at each substitution and would build with integers. A Rust generic function is checked once, and the error shows up right away, even if the function is never called.

Key points

  • You write a generic function fn largest<T>(…) once, and the compiler fills in T from the call's arguments.
  • The body is checked once for any T: without a bound T can do nothing, and a > b is error E0369.
  • The bound T: PartialOrd promises comparison and allows > in the body.
  • A generic type Point<T> gets methods through impl<T> Point<T>.