Lesson 2 · Unit 03
Generics
One definition for many types, static or dynamic
What you practise
- Generic functions and structs, compiled once per type,
impl Traitagainstdyn Trait, static against dynamic dispatch
Try a question from this lesson
Pick one
T can be any type at all, including types with no order. Which line does the compiler reject?
fn bigger<T>(a: T, b: T) -> T {
if a > b { a } else { b }
}
println!("{}", bigger(3, 9));Hint
The body is checked once, for every possible T, not for the types used in the calls.
Correct answer
Line 2
Why
A generic body may only do what every T can do, and not every type supports >: "binary operation > cannot be applied to type T". The call with integers does not rescue it.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Bounds unlock behaviour
A bare T can only be moved around. A trait bound narrows it: T: Clone accepts only types that implement Clone, and in return the body may call .clone().
Python checks such things when the line runs. Rust checks the body against the bound once, and every call against the bound too. Several bounds join with +.
fn pair<T: Clone>(x: &T) -> (T, T) {
(x.clone(), x.clone())
}
let p = pair(&String::from("hi"));
println!("{} {}", p.0, p.1);Concept
Compiled once per type
Generics cost nothing at run time. For every concrete type a generic function is used with, the compiler generates a separate specialised copy, as if you had written each by hand.
Every call then goes straight to the right copy, decided at compile time. This is static dispatch. The price is paid in compile time and program size.
Concept
dyn Trait
Sometimes the type is only known at run time, as in a list of mixed shapes. A trait object, dyn Area, is "some value that implements Area", used behind a pointer such as Box, which keeps the value on the heap.
Each call looks the method up in a table at run time: dynamic dispatch, the way every Python method call works.
trait Area {
fn area(&self) -> u32;
}
struct Sq(u32);
impl Area for Sq {
fn area(&self) -> u32 {
self.0 * self.0
}
}
let b: Box<dyn Area> = Box::new(Sq(3));
println!("{}", b.area());9 more exercises in the app
- 4× type the answer
- 1× fill the blanks
- 2× multiple choice
- 1× match the pairs
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.