Generic Functions

Generic Functions in Rust: A forklift driver's procedure is written entirely in terms of the pallet.

The Analogy: The Forklift That Never Sees The Cargo

A forklift driver's procedure is written entirely in terms of the pallet. Square up to the face, set the tines to the fork pockets, lift until the load is clear, tilt back a degree, carry low, set down square, withdraw straight. Not one step in that list mentions what is on the pallet. That is not laziness or an omission. It is the entire reason one machine and one written procedure serve a building holding bricks, paper, wine and frozen fish.

The procedure works precisely because it never opens the load. The driver cannot tell you which of two pallets is heavier by looking at them, cannot tell you what is inside either, and cannot decide that one should go out before the other on the grounds of what it contains. Everything the procedure does is positional: this pallet, from here, to there, in that order. Any statement the driver could make about the cargo would have to be a statement the procedure was given, and the procedure was given nothing.

Which is exactly what happens the moment a job needs cargo knowledge. Keep it upright. Do not stack two high. Put the heavier one on the bottom. None of those can be answered from the pallet, so the yard puts a label on the load -- a class, a rating, a symbol stencilled on the side -- and now the procedure can refer to the label instead of to the goods. The step reads "if the label says fragile, single-stack", and it still does not know what is inside. It knows only what the label promised.

There is also a blunter option: a procedure written for one kind of cargo and nothing else. The fish dock has its own rules, written for fish, that would be nonsense applied to paper. Both answers are legitimate, and this lesson is the first half of the picture: writing the procedure that never opens the load, seeing exactly how far that gets you, and walking into the wall where a label becomes unavoidable. The label is called a trait bound, and it arrives three lessons from now.


Syntax or Core Structure

A function declares its type parameters in angle brackets between the name and the argument list, and may then use them anywhere a type is expected:

fn first<T>(items: &[T]) -> Option<&T> {
    if items.is_empty() {
        None
    } else {
        Some(&items[0])
    }
}

fn swap<T>(pair: (T, T)) -> (T, T) {
    (pair.1, pair.0)
}

fn main() {
    let numbers = [10, 20, 30];
    let names = ["ana", "bo"];
    let nothing: [u8; 0] = [];

    println!("number {:?}", first(&numbers));
    println!("name   {:?}", first(&names));
    println!("empty  {:?}", first(&nothing));

    let s = swap((1, 2));
    let t = swap(("left", "right"));
    println!("swapped {:?} {:?}", s, t);
}

Output:

number Some(10)
name   Some("ana")
empty  None
swapped (2, 1) ("right", "left")

first was called at three element types and swap at two, and no call site named a type. Inference reads the argument and fills in the blank.

Two details in that signature are doing more work than they look. The parameter is &[T] rather than Vec<T>, so the function borrows rather than consuming, and an array, a Vec and a slice all coerce to it. The return type is Option<&T> rather than Option<T>, and that is not a stylistic choice: producing an owned T from a borrowed one requires copying it, copying is a capability, and a bare T has no capabilities. Handing back a reference is the only thing available.

The nothing binding needs its annotation for a reason worth noticing. An empty array literal gives the compiler nothing to infer the element type from, and first does not constrain it either, so [u8; 0] has to be written down. Inference is not magic; it is constraint solving, and an empty collection supplies no constraints.


Technical Depth: How Far A Bare Parameter Gets You

The list of things T can do

Inside fn f<T>(...), the type T has exactly one property: it exists. Every operation divides cleanly into things that are properties of the surrounding structure and things that are properties of the type.

Operation on a bare TAllowedReason
Move it, return it, put it in a VecYesEvery type in Rust can be moved
Take a reference to itYesReference-taking is not a capability of the type
Count, index, reorder, split a slice of themYesThe work is on the slice, not on the element
Drop itYesEvery type can be dropped
Compare two with > or ==NoNeeds PartialOrd or PartialEq
Print with {} or {:?}NoNeeds Display or Debug
Copy or clone oneNoNeeds Copy or Clone
Add two togetherNoNeeds Add
Call any method on itNoT has no known methods at all

The first four are the whole toolkit, and they are enough for a surprising amount of real code: anything about position, order, length or ownership.

The wall, exactly where the book puts it

The canonical demonstration is the function everybody writes second:

fn largest<T>(items: &[T]) -> &T {
    let mut best = &items[0];

    for item in items {
        if item > best {
            best = item;
        }
    }

    best
}

Every line of that is correct reasoning and it does not compile. The compiler rejects it with E0369, reporting that the binary operation cannot be applied to type &T, and then does something unusually helpful: it names the fix, suggesting that T be restricted with PartialOrd. That suggestion is a trait bound, it is the subject of the fifth lesson in this module, and until then largest genuinely cannot be written generically. Notice that the error is not about references -- adding or removing an ampersand does not help, because the missing thing is a capability of T and no amount of borrowing conjures one.

One function in, several functions out

A generic function is a template. The compiler produces one real function per instantiation you use, and the clearest proof is to ask inside the body for something that differs per type:

fn tag<T>(_item: &T) -> usize {
    std::mem::size_of::<T>()
}

fn main() {
    let a: u8 = 1;
    let b: u64 = 1;
    let c: [u32; 3] = [1, 2, 3];

    println!("u8      {}", tag(&a));
    println!("u64     {}", tag(&b));
    println!("[u32;3] {}", tag(&c));
}

Output:

u8      1
u64     8
[u32;3] 12

Three different constants out of one written body. There is no runtime lookup here; size_of::<T>() is a compile-time constant folded into each of the three compiled copies, and each copy is as fast as if you had written it by hand. The cost is the same one as in the previous lesson: three copies is three copies, in compile time and in binary size.

Sizes as parameters

Types are not the only thing that can be left blank. A const parameter takes a value, which is how a function can be generic over array length:

fn sum_row<const N: usize>(row: [u32; N]) -> u32 {
    let mut total = 0;

    for v in row {
        total += v;
    }

    total
}

fn main() {
    println!("3 wide {}", sum_row([1, 2, 3]));
    println!("5 wide {}", sum_row([10, 20, 30, 40, 50]));
}

Output:

3 wide 6
5 wide 150

Two instantiations again, N = 3 and N = 5, each with the length known as a constant. In practice &[u32] would be the ordinary signature here and would accept both without any parameter at all; const generics earn their keep when the length has to appear in the return type or in a stored field.

Passing in the missing capability

There is one honest way to make a bound-free generic function do real work on its elements: have the caller hand over the behaviour. A function pointer is an ordinary type and can be a parameter like any other.

fn apply_all<T, U>(items: Vec<T>, f: fn(T) -> U) -> Vec<U> {
    let mut out = Vec::new();

    for item in items {
        out.push(f(item));
    }

    out
}

fn doubled(n: i32) -> i32 {
    n * 2
}

fn shout(word: String) -> String {
    word + "!"
}

fn main() {
    let numbers = apply_all(vec![1, 2, 3], doubled);
    let words = apply_all(vec![String::from("go"), String::from("stop")], shout);

    println!("numbers {:?}", numbers);
    println!("words   {:?}", words);
}

Output:

numbers [2, 4, 6]
words   ["go!", "stop!"]

apply_all still knows nothing about T or U. It knows that something turns one into the other, because it was handed that something. Two parameters, two inferred pairs of types, one written body.

The fn type has a real limit, and it is worth knowing now rather than discovering it later. fn(T) -> U is a plain function pointer: it accepts named functions and closures that capture nothing at all. A closure that captures a variable from its environment is a different type and will not coerce, so apply_all(v, |x| x * factor) is rejected the moment factor comes from outside. The general version of this parameter is written with the Fn traits, and it is Module 7's business.


Real World Example: One Paging Helper For Three Endpoints

Three endpoints of a small service each return a list: users, invoices, audit entries. Each needs the same thing -- take page N of a collection, and report how many pages there are so the caller can draw the controls. The arithmetic is identical every time and it has an off-by-one in it that is worth getting wrong only once.

struct Page<T> {
    items: Vec<T>,
    page: usize,
    of_pages: usize,
    total: usize,
}

fn paginate<T>(mut items: Vec<T>, page: usize, per_page: usize) -> Page<T> {
    let total = items.len();

    let of_pages = if per_page == 0 {
        0
    } else {
        (total + per_page - 1) / per_page
    };

    if page == 0 || page > of_pages {
        return Page { items: Vec::new(), page, of_pages, total };
    }

    let mut kept = items.split_off((page - 1) * per_page);
    kept.truncate(per_page);

    Page { items: kept, page, of_pages, total }
}

fn render<T>(p: &Page<T>, line: fn(&T) -> String) -> String {
    let mut out = format!("page {} of {} ({} total)\n", p.page, p.of_pages, p.total);

    if p.items.is_empty() {
        out.push_str("  (no rows)\n");
    }

    for item in &p.items {
        out.push_str("  ");
        out.push_str(&line(item));
        out.push('\n');
    }

    out
}

struct User {
    login: String,
    admin: bool,
}

struct Invoice {
    number: u32,
    pence: u32,
}

fn user_line(u: &User) -> String {
    let role = if u.admin { "admin" } else { "member" };
    format!("{} ({})", u.login, role)
}

fn invoice_line(i: &Invoice) -> String {
    format!("#{} {}.{:02}", i.number, i.pence / 100, i.pence % 100)
}

fn audit_line(s: &String) -> String {
    s.clone()
}

fn main() {
    let users = vec![
        User { login: String::from("ana"), admin: true },
        User { login: String::from("bo"), admin: false },
        User { login: String::from("cai"), admin: false },
        User { login: String::from("dee"), admin: true },
        User { login: String::from("eze"), admin: false },
    ];

    let invoices = vec![
        Invoice { number: 1041, pence: 25000 },
        Invoice { number: 1042, pence: 899 },
        Invoice { number: 1043, pence: 120050 },
    ];

    let audit = vec![String::from("login ana"), String::from("role change bo")];

    print!("{}", render(&paginate(users, 2, 2), user_line));
    print!("{}", render(&paginate(invoices, 1, 5), invoice_line));
    print!("{}", render(&paginate(audit, 3, 1), audit_line));
}

Output:

page 2 of 3 (5 total)
  cai (member)
  dee (admin)
page 1 of 1 (3 total)
  #1041 250.00
  #1042 8.99
  #1043 1200.50
page 3 of 2 (2 total)
  (no rows)

Everything paginate does is arithmetic on lengths. It never looks at a user, an invoice or a string, and it could not if it wanted to. The ceiling division that turns five rows and a page size of two into three pages is written once, and the three endpoints cannot drift apart on it, because there is one copy. Compare the alternative honestly: three hand-written paging routines, and the third one is where the off-by-one lives.

render is the more interesting half, because it needs something a bare T cannot do -- turn a row into text. Rather than requiring a capability it has no way to name yet, it takes one as an argument: fn(&T) -> String. The caller supplies the knowledge, and the three line functions are the three places where the domain lives. This has a visible cost in audit_line, which has to be written fn audit_line(s: &String) rather than the idiomatic &str, because the signature is derived mechanically from T and T is String. That awkwardness is the honest price of not having bounds yet; with Display as a bound the line parameter disappears from every call site entirely, and that is the fifth lesson of this module.

There are three compiled copies of paginate and three of render in the finished binary, one per element type, and Page<User>, Page<Invoice> and Page<String> are three unrelated types of three different sizes. One thing about the design is slower than it looks, though: calling f(item) through a function pointer is an indirect call the optimiser usually cannot inline, whereas a monomorphized trait bound is a direct call it usually can. For rendering a page of rows that is invisible. For a function called in a tight loop it would not be.

Four honest limits. page 3 of 2 is what the last line reports, because the function hands back both what you asked for and what exists rather than clamping -- defensible for an API that wants to say "that page is gone", wrong for a UI that wants to show the last page, and the code does not say which it intended. paginate takes the entire collection by value and discards the part before the page, so it is linear in the total and hopeless against a database, where the paging has to be pushed down into the query as LIMIT and OFFSET. An empty collection produces zero pages, so page one of an empty list reports page 1 of 0, which is arithmetically consistent and reads like a bug. And render builds the whole page into one String before anything is printed, which is fine for twenty rows and not for twenty thousand.


Common Mistakes

  1. Comparing, printing or adding a bare T. The errors are E0369 and E0277 and they are not bugs in your reasoning -- they are the compiler pointing out that the capability was never requested. Read the help line; it names the bound.
  1. Returning T when the function only has a &T. Producing an owned value out of a borrowed one needs Clone or Copy. Until then the honest signature returns a reference.
  1. A type parameter that appears nowhere in the signature. On a function this compiles, but nothing can infer it, so every call needs a turbofish and the parameter is pure friction. On a struct it is a hard error, E0392, unless you store a PhantomData.
  1. Passing an owned collection where a slice is wanted. first(numbers) fails where first(&numbers) succeeds; the coercion from &Vec<T> to &[T] is automatic, but there is no coercion out of an owned value.
  1. Assuming a generic function costs something at runtime. It does not. After monomorphization there is no genericity left, no lookup and no indirection -- which is precisely why there is a copy per instantiation.
  1. Handing a capturing closure to an fn parameter. A closure that captures anything is its own type and will not coerce to a function pointer. The error mentions closures and function pointers together, and the real fix is the Fn traits in Module 7.
  1. Taking Vec<T> by value in order to read one element. The function now owns and destroys the caller's collection to answer a question about it. Take &[T].
  1. Turbofishing the wrong arity. apply_all::<i32>(...) on a two-parameter function is an error about the number of generic arguments, not about types; the fix is either both or neither.
  1. Naming everything T. In a function with three parameters, T, U and V tell the reader nothing. Row, Key and Rendered cost nothing and appear in every error message the caller ever sees.

Best Practices

  • Take &[T] and return Option<&T> by default. Ownership is a requirement to justify, not a starting point.
  • Let the argument types drive inference and reach for a turbofish only where there is genuinely nothing to infer from -- an empty collection, or a parameter that appears only in the return type.
  • Keep the structural work generic and the type-aware work concrete. If a function body needs to know what T is, that body probably belongs somewhere else.
  • When a generic function needs behaviour it cannot name, take it as a parameter rather than restricting the function to one type. A fn(&T) -> String argument is a stopgap with a real cost, and it is a much better stopgap than three copies of the function.
  • Read the compiler's help line on E0369 and E0277 as a specification. It tells you exactly which bound to write once you know how.
  • Write the concrete function first when there is one caller. Generalise when there are two, and only if the two bodies would have been identical.
  • Use const parameters only when the length has to escape the function -- into a return type or a stored field. Otherwise a slice is simpler and accepts more.
  • Give parameters names that mean something as soon as they have a role, and keep the count down. Every extra parameter is another thing the caller has to pin down.

Practice Exercises

  1. Add last<T> and nth<T> alongside first, both returning Option<&T>, and write nth so it cannot panic on an out-of-range index. Then explain in one sentence why neither can return Option<T>.
  1. Write the largest function out, compile it, and copy down the exact bound the compiler suggests. Do not add it. Instead, write a version that works today by taking the comparison as a parameter, and say what its signature has to be.
  1. Change paginate so an out-of-range page clamps to the last page instead of returning nothing, keeping total accurate. Then name one caller that would have preferred the original behaviour and say how it would tell the difference.
  1. Add a keep: fn(&T) -> bool parameter to paginate, applied before the page is taken. Decide whether total counts rows before or after filtering, implement your choice, and say which one the page controls in a UI actually need.