Module 6Lifetimes & LabLesson 7 of 822 min
Lifetimes Introduction
Why lifetimes exist; reading signatures that return references.
The problem
References must not outlive their data.
rust
fn longest<a>(x: &a str, y: &a str) -> &a str {
if x.len() >= y.len() { x } else { y }
}Elision
Many functions need no annotations. Annotate when returning references tied to inputs.
Escape hatch
Return owned String/Vec when unsure.
Challenge
Write first_positive(xs: &[f64]) -> Option<&f64>.
Tips
- Compile-time only
- Owned data avoids issues
- Add annotations when compiler asks
Try it live
Lifetimes IntroductionRust 2021
Loading editor…
Output
Press Run to compile and execute.