Lesson 2 · Unit 07
Generics and lifetimes
A placeholder for a type, trait bounds, and the lifetime the compiler asks for
What you practise
- Generic functions and structs, trait bounds, and lifetimes at the one place the compiler asks: returning a reference
Try a question from this lesson
Pick one
Two functions that each return the first item of a vector. Apart from their names, what is different between them?
fn first_i32(v: &Vec<i32>) -> i32 {
v[0]
}
fn first_char(v: &Vec<char>) -> char {
v[0]
}Correct answer
Only the types they mention
Why
The bodies are identical. Only i32 and char differ. Writing the same function once per type does not scale. Rust lets you write it once, with a placeholder where the type goes.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
A placeholder for a type
<T> after a function's name introduces a type parameter: a placeholder for whatever type the caller uses. Such a function is called generic.
You have used generic types all along. Vec<i32> and Vec<String> are the same Vec<T> with a different T.
fn swap<T>(a: T, b: T) -> (T, T) {
(b, a)
}
let nums = swap(1, 2);
let words = swap("hi", "yo");
println!("{:?} {:?}", nums, words);Concept
Generic structs
A struct can take a type parameter too. Pair<T> holds two values of one type, whatever that type is.
Its methods go in impl<T> Pair<T>, with a bound if they need one. The standard library builds Vec<T>, Option<T> and Result<T, E> this way: one definition, any type inside.
struct Pair<T> { a: T, b: T }
impl<T: PartialOrd> Pair<T> {
fn sorted(&self) -> bool {
self.a <= self.b
}
}
let p = Pair { a: 3, b: 8 };
let q = Pair { a: "pear", b: "fig" };
println!("{} {}", p.sorted(), q.sorted());Concept
Lifetimes: which borrow comes back?
A function that returns a borrow must be clear about what it is borrowed from. With one borrowed parameter there is no doubt, and you write nothing extra.
With two, you must say. 'a is a lifetime name. Here it ties the result to both a and b: the result may be used only while both are still alive.
fn longest<'a>(a: &'a str, b: &'a str)
-> &'a str {
if a.len() > b.len() { a } else { b }
}
println!("{}", longest("fig", "pear"));9 more exercises in the app
- 2× type the answer
- 4× multiple choice
- 2× fill the blanks
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.