Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ REUSE THE IDEA
BUILD NOTE 24 / 53

One algorithm, many concrete types.

Express reusable code without discarding type information.

BY NAVAN SAMI◷ 7 MIN READFOUNDATIONSRUST 2024

01 Understand the contract

A generic parameter stands for a type chosen by the caller or inferred from usage. The function body still has to be valid for its declared bounds. Rust normally monomorphizes generic functions into concrete versions used by the program, so generic code does not automatically imply dynamic dispatch. Start with the operations the algorithm needs and express those as bounds. Prefer a small clear generic function over a highly abstract signature that makes everyday calls hard to understand.

02 Make it concrete

This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.

lessons/generics/src/main.rs
fn first<T>(values: &[T]) -> Option<&T> {
    values.first()
}
fn main() {
    println!("{:?}", first(&[3, 5]));
    println!("{:?}", first(&["Rust", "Python"]));
}
↳ EXPECTED OUTPUT
Some(3)
Some("Rust")
  1. 1

    T is inferred separately at the two calls.

  2. 2

    The function borrows any element type.

  3. 3

    No Copy bound is necessary because it returns a reference.

From the extracted rust-workbench folder
cargo run -p lesson_generics

03 Mind the boundary

04 Your next build

A SMALL MISSION

Write last<T> returning an optional reference and test it with integers and an empty slice.

Reveal one possible solution +
solutions/generics/src/main.rs
fn last<T>(values: &[T]) -> Option<&T> {
    values.last()
}
fn main() {
    assert_eq!(last(&[2, 7]), Some(&7));
    assert_eq!(last::<u8>(&[]), None);
}

05 Check your reasoning

QUICK SIGNAL CHECK

Why does first<T> not need T: Copy?

ONE MORE CONTRACT YOU CAN EXPLAIN.

Understand it.
Then make it yours.

Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.