Structs with References and Lifetimes


The following lifetimes program shows a struct whose fields are references. A Book<'a> does not own its title and author; it borrows them from Strings that live elsewhere. The lifetime parameter 'a lets the compiler check that a Book never outlives the data it borrows.

Lifetimes do not always have to be written out. In function signatures, Rust fills them in using three lifetime elision rules:

  1. Each reference parameter gets its own lifetime.
  2. If there is exactly one input lifetime, every output reference gets that lifetime.
  3. If one of the parameters is &self or &mut self, every output reference gets the lifetime of self.

The comments in the program mark each lifetime as REQUIRED (the code does not compile without it), ELIDED (Rust infers it using the rules above), or EXPLICIT (by choice). The last case is author(), where writing &'a str instead of relying on elision lets the result outlive the Book. The end of main has commented-out code that fails to compile because a Book would outlive the String it borrows from.

This zip file contains the complete crate.

src/main.rs