Module lessons (1/2)
Lifetime Explicits ('a), Elision and 'static
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
rustcand 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
- 11. When
'ais needed in functions - 22. The 3 rules of Lifetime Elision
- 33. Lifetime in
struct - 44. The lifetime
'static - 5Practical exercises
- 6Check for understanding
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.