Lifetimes can be explored in a few steps:
- Create a new project using cargo new lifetimes --lib and open it in your favorite editor.
- Let's start with a simple function that takes in a reference that might not outlive the function! Let's make sure that the function and the input parameter are on the same lifetime:
// declaring a lifetime is optional here, since the compiler automates this////// Compute the arithmetic mean/// pub fn mean<'a>(numbers: &'a [f32]) -> Option<f32> { if numbers.len() > 0 { let sum: f32 = numbers.iter().sum(); Some(sum / numbers.len() as f32) } else { None }}
- Where the lifetime declaration is required is in structs. Therefore, we define the base struct first. It comes with a lifetime annotation ...