← العودة إلى الدورة: Rust from scratch

Lifetimes and week 6 review

الفيديو قريبًا

Lifetimes have a reputation for being the hardest part of Rust, but the underlying idea is simple: every reference is valid for some time, and the compiler checks that it is never used outside that time. You saw the informal version in week 3: a reference cannot outlive the data it points to. Most of the time the compiler infers lifetimes by itself. Only when a function or struct has references and the compiler cannot guess the relationship between them, you must annotate it yourself.

Annotations on functions

Imagine a function that receives two &str and returns the longer one. Does the returned reference point to the first or the second? The compiler does not know, so it cannot ensure how long it will remain valid. With the <'a> annotation you tell it: "the returned reference lives, at most, as long as both inputs live". The annotation does not change how long anything lives; it only describes the relationship so the compiler can verify it. The first example does not compile on purpose.

rust
// Does NOT compile on purpose: error[E0106] missing lifetime specifier
fn longest(a: &str, b: &str) -> &str {
    if a.len() >= b.len() { a } else { b }
}

fn main() {
    println!("{}", longest("abc", "de"));
}
rust
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
    if a.len() >= b.len() { a } else { b }
}

fn main() {
    let first = String::from("long string");
    let result;
    {
        let second = String::from("short");
        result = longest(first.as_str(), second.as_str());
        println!("inside: {result}");
    } // second ends here
    // println!("{result}"); // would not compile: result may point to second
}

Read the annotation like this: "for some lifetime 'a, both parameters and the result live at least 'a". If you used result after second ended, the compiler would reject it, because result might be pointing to second. That is exactly the error that in C would be an access to already freed memory. A practical rule to know whether you need to annotate: if a function returns a reference, that reference must come from some parameter; lifetimes say which one.

Lifetimes in structs and elision

If a struct holds a reference, it must declare the lifetime: struct Excerpt<'a> { part: &'a str }. It means the struct cannot outlive the text it borrows from. On the other hand, in simple functions you write nothing thanks to the elision rules: with a single reference parameter, the output uses that same lifetime; in a method with &self, the output uses the lifetime of self. That is why fn first_word(s: &str) -> &str needed no annotations. Finally, 'static is the lifetime that lasts the whole program: text literals have it.

rust
struct Excerpt<'a> {
    part: &'a str,
}

impl<'a> Excerpt<'a> {
    fn level(&self) -> usize {
        self.part.len()
    }
    // elision: output gets the lifetime of &self
    fn first_char(&self) -> &str {
        &self.part[..1]
    }
}

fn main() {
    let novel = String::from("Call me Ishmael. Some years ago...");
    let first_sentence = novel.split('.').next().unwrap();
    let excerpt = Excerpt { part: first_sentence };
    println!("{} {} {}", excerpt.part, excerpt.level(), excerpt.first_char());

    let literal: &'static str = "lives for the whole program";
    println!("{literal}");
}

Week 6 review

  • A trait defines behavior; it is implemented with impl Trait for Type, can have default methods and is accepted as a parameter with impl Trait, with bounds T: Trait or as a dyn Trait object.
  • Generics (T) avoid duplicated code; trait bounds say what T can do; the compiler generates one version per type.
  • Lifetimes ('a) describe how long a reference is valid and are annotated when the compiler cannot infer them, mostly in functions that return references and in structs that store them.
rust
fn shorter<'a>(a: &'a str, b: &'a str) -> &'a str {
    if b.len() < a.len() { b } else { a }
}

struct Parser<'a> {
    text: &'a str,
}

impl<'a> Parser<'a> {
    fn words(&self) -> Vec<&str> {
        self.text.split(' ').collect()
    }
}

fn main() {
    println!("{}", shorter("rust", "go"));
    let p = Parser { text: "one two three" };
    println!("{:?} ({})", p.words(), p.words().len());
}

اختبر ما تعلمته

السؤال 1 من 6

What does a lifetime annotation like 'a describe?

✎ ملاحظاتي

محفوظ في هذا المتصفح فقط. سجّل الدخول لحفظه في حسابك.0/5000 حرف

← السابقالتالي →