Skip to main content
Module 6 · Lesson 1 of 211/24 in the course~22 min
Module lessons (1/2)

Lifetime Explicits ('a), Elision and 'static

Lesson preview5 hands-on exercises readyCourse Rust · Module 6 — Lifetimes & Smart Pointers

Note 'a parameters in signatures that return references, understand the 3 elision rules, struct with references and 'static.

What you'll learn in this lesson

  • Understand why lifetimes describe relationships between lifetimes of existing references without changing their actual lifetimes.
  • Note generic signatures (fn longest<'a>(x: &'a str, y: &'a str) -> &'a str) and structs holding loans (struct Excerpt<'a>).
  • Recognize the three rules of elision of rustc and the exact meaning of 'static.

Overview

Each reference in Rust has a lifetime (the scope in which the pointed data remains valid). In 95% of cases the compiler deduces it automatically; when you return a reference by choosing between multiple inputs, you must declare the binding explicitly with 'a.

Imagine a function that compares two slices and returns the longest. At compile-time rustc doesn't know which branch will be taken at runtime, so it can't know whether the output comes from left or right:

Sections covered in this lesson

  1. 11. When 'a is needed in functions
  2. 22. The 3 rules of Lifetime Elision
  3. 33. Lifetime in struct
  4. 44. The lifetime 'static
  5. 5Practical exercises
  6. 6Check for understanding
Pro Lesson · Module 6 — Lifetimes & Smart Pointers

Unlock "Lifetime Explicits ('a), Elision and 'static" and the full Course Rust curriculum

Note `'a` parameters in signatures that return references, understand the 3 elision rules, struct with references and `'static`.

Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.

  • Instant access to all advanced modules in Course Rust plus 17 more courses
  • Hands-on browser exercises with automated test suites and solutions
  • 14-day money-back guarantee processed via Paddle.com

14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.