Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Lecture 30 - Generics: one function, many types

Different shapes passing through a single slot

Announcements




Learning objectives

By the end of today, you should be able to:

  • Write generic functions and structs using type parameters
  • Use trait bounds to say what a generic type has to be able to do
  • Explain what the compiler does with a generic function, and why it costs nothing at run time
  • Recognize the generics we've been using all along

Warm-up: name a trait

Consider: a dog, a goldfish, a parrot.

🐕 🐟 🦜

Try to name a trait that two of them have and the third doesn't.

Now a function: take_for_a_walk(pet). Which of the three can I call it on?

Put this on a map

I have a function that puts a thing on a map. Which of these should I be able to call it on?

  • a street address
  • a building name, like Warren Towers
  • a latitude and longitude
  • a person
  • a photo
  • a ZIP code
  • a phone number
  • a pizza

Think, then pair. Which ones work, and what do those things have in common?

Sort this pile

Same two questions, for a function that sorts a pile:

  • a hand of playing cards
  • a shelf of books
  • a jar of coins
  • a stack of receipts
  • a waiting room of patients at the ER
  • a team of soccer players
  • a bag of marbles

Here's the idea: every function, implicitly, has a list like this.

Python never makes it explicit, so you only find out you're a pizza when the code bugs out.

Rust makes you specify what you need in the signature, and then the function works on everything that meets it.

One max, many types

In Python, one function handles every type we throw at it:

def max(x, y):
    return x if x > y else y
>>> max(3, 2)
3
>>> max(3.1, 2.2)
3.1
>>> max('s', 't')
't'

From the pre-work: how do you think Rust does this?

What Python's flexibility costs

  • Python works out what > means for these two values every time the function is called, while the program runs
  • A bad call isn't caught until that line runs
>>> max(3, 'a')
TypeError: '>' not supported between instances of 'int' and 'str'

Rust without generics

Every parameter in Rust has a type, so with what we know so far it's one function per type:

fn max_i32(x: i32, y: i32) -> i32 {
    if x > y { x } else { y }
}

fn max_f64(x: f64, y: f64) -> f64 {
    if x > y { x } else { y }
}

fn max_char(x: char, y: char) -> char {
    if x > y { x } else { y }
}

fn main() {
    println!("{}", max_i32(3, 8));      // 8
    println!("{}", max_f64(3.3, 8.1));  // 8.1
    println!("{}", max_char('a', 'b')); // b
}

Every call is checked before the program runs. But supporting N types = writing N functions, all with the same body.

We want Python's one function with Rust's early checking. That's what generics are for.

A first generic function

fn passit<T>(x: T) -> T {
    x
}

fn main() {
    let x = passit(5);
    println!("x is {}", x);      // x is 5

    let x = passit(1.1);
    println!("x is {}", x);      // x is 1.1

    let x = passit('s');
    println!("x is {}", x);      // x is s
}

The <T> after the name makes the function generic. T is a placeholder for a type, filled in at each call: i32, then f64, then char.

This one works because it does nothing with x except hand it back.

T is only a name, short for "type". You'll also see U for a second type, E for an error type, and K and V for keys and values on Friday.

Okay, but that was pretty boring...

Let's write the one we wanted:

fn max<T>(x: T, y: T) -> T {
    if x > y { x } else { y }
}

fn main() {
    println!("{}", max(5, 10));
}
error[E0369]: binary operation `>` cannot be applied to type `T`
help: consider restricting type parameter `T` with trait `PartialOrd`

T could be any type at all, and plenty of types have no >. On Monday, Striker didn't. Rust won't let a generic function do something only some types can do.

Trait bounds: say what T has to be able to do

fn max<T: PartialOrd>(x: T, y: T) -> T {
    if x > y { x } else { y }
}

#[derive(Debug, PartialEq)]
struct Striker { goals: u32, name: String }

fn main() {
    println!("{}", max(5, 10));        // T = i32
    println!("{}", max(3.14, 2.7));    // T = f64
    println!("{}", max('a', 'b'));     // T = char

    let messi = Striker { goals: 20, name: String::from("Messi") };
    let haaland = Striker { goals: 27, name: String::from("Haaland") };
    // println!("{:?}", max(messi, haaland));
}

T: PartialOrd is a trait bound. It reads as "any type T, as long as it implements PartialOrd."

Inside the function we can use exactly what the bound promises. The compiler works out T at each call from the arguments.

Write the body first and let the compiler name the bound. Its help line said "consider restricting type parameter T with trait PartialOrd", and that was the whole fix.

Monday's &impl Trait was this in disguise

// Monday
fn print_card(item: &impl Describe) {
    println!("{}", item.describe());
}

// The same function, written out
fn print_card<T: Describe>(item: &T) {
    println!("{}", item.describe());
}

Both say: a reference to any type that implements Describe.

  • &impl Trait is shorter, and fine for one parameter
  • <T: Trait> gives the type a name. We need the name when two things have to be the same type, like the x and y in max

Activity 30, Problem 1: keep both

See Problem 1 on Activity 30.

Answer. Three things change, and each one forces the next:

fn max<T: PartialOrd + Clone>(x: &T, y: &T) -> T {
    if *x > *y { x.clone() } else { y.clone() }
}

let bigger = max(&a, &b);   // a and b are only borrowed
  1. Borrow the arguments: &T in the signature, &a and &b at the call
  2. A borrowed x can't be handed back as an owned T, so return a clone
  3. .clone() only gives back a T when T is Clone, so add the bound

What the compiler does with a generic function

It looks at every call, sees which types T gets, and writes a separate copy of the function for each one.

// What we write:
fn max<T: PartialOrd>(x: T, y: T) -> T {
    if x > y { x } else { y }
}

fn main() {
    println!("{}", max(5, 10));
    println!("{}", max(3.14, 2.7));
}
// What the compiler generates (roughly):
fn max_i32(x: i32, y: i32) -> i32 {
    if x > y { x } else { y }
}

fn max_f64(x: f64, y: f64) -> f64 {
    if x > y { x } else { y }
}

fn main() {
    println!("{}", max_i32(5, 10));
    println!("{}", max_f64(3.14, 2.7));
}

That's the code we wrote by hand at the start of class. The compiler wrote it for us.

The name for this is monomorphization. max<T> is polymorphic (many shapes), and each compiled copy is monomorphic (one shape).

Generic structs

#[derive(Debug)]
struct Point<T> {
    x: T,
    y: T,
}

let int_point = Point { x: 5, y: 10 };        // Point<i32>
let float_point = Point { x: 3.14, y: 2.7 };  // Point<f64>

Point<i32> and Point<f64> are two different types, with different sizes:

Stack:
┌────────────────────────────────┐
│ main()                         │
│ ├ int_point: Point<i32>        │
│ │  ├ x: i32 = 5                │  4 bytes
│ │  └ y: i32 = 10               │  4 bytes
│ └ float_point: Point<f64>      │
│    ├ x: f64 = 3.14             │  8 bytes
│    └ y: f64 = 2.7              │  8 bytes
└────────────────────────────────┘

Methods on generic structs

#[derive(Debug)]
struct Point<T> {
    x: T,
    y: T,
}

impl<T> Point<T> {
    fn new(x: T, y: T) -> Point<T> {
        Point { x, y }
    }

    fn get_x(&self) -> &T {
        &self.x
    }
}

fn main() {
    let point1 = Point::new(1, 2);      // Point<i32>
    let point2 = Point::new(1.5, 2.5);  // Point<f64>
    println!("{}", point1.get_x());
    println!("{}", point2.get_x());
}

impl<T> introduces the name T, and Point<T> uses it. These methods exist for every Point, whatever T is.

The bounds we'll use most

use std::fmt::Debug;

// Debug: can be printed with {:?}
fn debug_value<T: Debug>(val: T) {
    println!("Value: {:?}", val);
}

// Clone: can be duplicated with .clone()
fn duplicate<T: Clone>(val: &T) -> T {
    val.clone()
}

// Copy: copied automatically, never moved
fn two_of<T: Copy>(val: T) -> (T, T) {
    (val, val)
}

fn main() {
    debug_value(vec![1, 2]);
    println!("{}", duplicate(&String::from("hi")));
    println!("{:?}", two_of(7));
}

Naming Debug in a bound needs use std::fmt::Debug;, even though #[derive(Debug)] never did. Forget it and the error is "expected trait, found derive macro Debug".

Clone, Copy, PartialEq, and PartialOrd need no use.

More than one bound: + and where

use std::fmt::Debug;

fn show_larger<T: PartialOrd + Debug>(x: T, y: T) {
    if x > y {
        println!("{:?}", x);
    } else {
        println!("{:?}", y);
    }
}

The same function, with the bounds moved to a where clause:

fn show_larger<T>(x: T, y: T)
where
    T: PartialOrd + Debug,
{
    if x > y {
        println!("{:?}", x);
    } else {
        println!("{:?}", y);
    }
}

where reads better once there are several bounds, or several type parameters.

We've been using generics all along

let maybe_number: Option<i32> = Some(42);
let outcome: Result<i32, String> = Ok(42);
let numbers: Vec<i32> = vec![1, 2, 3];
let boxed: Box<i32> = Box::new(5);

Now we know what the angle brackets mean. Here's how the standard library defines two of them:

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

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

Option<i32> is that enum with T filled in as i32. Result<i32, String> holds an i32 on success and a String on error.

Zero-cost abstractions

On Monday, a Box<dyn Agent> found the right name() while the program ran: follow a pointer, look up the method, call it. That lookup happens on every call.

A generic function has nothing to look up. By the time the program runs, max(5, 10) is already a call to the i32 copy.

Generics, <T: Trait>Trait objects, Box<dyn Trait>
Which code runs is decidedwhen compilingwhile running
Cost per callnoneone lookup
Mixed types in one Vecnoyes

"What you don't use, you don't pay for. What you do use, you couldn't hand code any better."

Bjarne Stroustrup, about C++ (but applies to Rust!)

E.g. Vec<T> is as fast as an array written by hand for one type.

A few weeks ago we said Rust moved the cost from run time to your time. Generics are the same trade: you and the compiler do more work up front, and the running program does less.

Activity 30

See Activity 30. Problem 1 is done, so start at Problem 2.

Appendix: methods that only exist for some types

Type-specific implementations

We can also write methods for one specific T:

#[derive(Debug)]
struct Point<T> {
    x: T,
    y: T,
}

// Works for any type T
impl<T> Point<T> {
    fn new(x: T, y: T) -> Point<T> {
        Point { x, y }
    }
}

// Only for Point<i32>
impl Point<i32> {
    fn distance_from_origin(&self) -> f64 {
        ((self.x.pow(2) + self.y.pow(2)) as f64).sqrt()
    }
}

// Only for Point<f64>
impl Point<f64> {
    fn distance_from_origin(&self) -> f64 {
        (self.x.powi(2) + self.y.powi(2)).sqrt()
    }
}

fn main() {
    let int_point = Point::new(3, 4);
    println!("Distance: {}", int_point.distance_from_origin()); // 5

    let float_point = Point::new(3.0, 4.0);
    println!("Distance: {}", float_point.distance_from_origin()); // 5

    // let char_point = Point::new('a', 'b');
    // char_point.distance_from_origin();
}
  • Some methods only make sense for certain types. What's the distance from the origin to ('a', 'b')? Uncomment the two char_point lines and run: "no method named distance_from_origin found for struct Point<char>"
  • Different types sometimes need different code: pow for integers, powi for floats

Trait bounds on methods

Some methods only make sense for some types. Let's write one that swaps x and y:

#[derive(Debug)]
struct Point<T> {
    x: T,
    y: T,
}

impl<T> Point<T> {
    fn new(x: T, y: T) -> Point<T> {
        Point { x, y }
    }

    fn swap(&mut self) {
        let temp = self.x;
        self.x = self.y;
        self.y = temp;
    }
}

fn main() {
    let mut point = Point::new(2, 3);
    point.swap();
    println!("{:?}", point);
}
error[E0507]: cannot move out of `self.x` which is behind a mutable reference

We've seen this error before. self is borrowed, so we can't move a value out of it.

If T is i32, let temp = self.x is a copy and everything's fine. If T is String, it's a move. The compiler has to assume T could be either.

Put the bound on the impl

#[derive(Debug)]
struct Point<T> {
    x: T,
    y: T,
}

impl<T> Point<T> {
    fn new(x: T, y: T) -> Point<T> {
        Point { x, y }
    }
}

// swap only exists for types that are Copy
impl<T: Copy> Point<T> {
    fn swap(&mut self) {
        let temp = self.x;  // a copy, since T is Copy
        self.x = self.y;
        self.y = temp;
    }
}

fn main() {
    let mut point = Point::new(2, 3);
    println!("{:?}", point);  // Point { x: 2, y: 3 }
    point.swap();
    println!("{:?}", point);  // Point { x: 3, y: 2 }
}

impl<T: Copy> means "these methods only exist when T is Copy." A Point<i32> can swap. A Point<String> can't, and the compiler says so.

(The compiler's own suggestion was Clone, which also works, with a .clone() on each line.)