Generic functions and types
What you'll learn:
- write one function and one struct for many types at once;
- explain why a
Twith no bound can do nothing, and add the boundT: 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.

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:
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:
- The bodies match word for word:
if a > b { a } else { b }. - Only the types in the header differ:
i32in the first andcharin the second. f64would need a third copy,u8a 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:
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 parameterT;: PartialOrdrequires values of typeTto be comparable with>and<;(a: T, b: T)— both arguments have the same typeT;-> 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.
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:
struct Point<T>declares a point with a type parameter, and both fieldsxandyhave typeT.impl<T> Point<T>holds methods for a point with anyT. The first<T>, afterimpl, declares the parameter; the second says which type the methods belong to.- The method
xreturns a reference&Tto the field. You cannot take the field out of&self:Tmay turn out to be aStringrather than aCopytype, so the method lends the value. Point { x: 1.5, y: 0.5 }is aPoint<f64>, andPoint { x: 1, y: 2 }would be aPoint<i32>. Here, too, the compiler infers the type.- 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:
fn largest<T>(a: T, b: T) -> T {
if a > b { a } else { b } // ✗
}
fn main() {
println!("{}", largest(7, 3));
}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 inTfrom the call's arguments. - The body is checked once for any
T: without a boundTcan do nothing, anda > bis error E0369. - The bound
T: PartialOrdpromises comparison and allows>in the body. - A generic type
Point<T>gets methods throughimpl<T> Point<T>.