How to do it...

Lifetimes can be explored in a few steps:

  1. Create a new project using cargo new lifetimes --lib and open it in your favorite editor.
  2. 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    }} 
  1. Where the lifetime declaration is required is in structs. Therefore, we define the base struct first. It comes with a lifetime annotation ...

Get Rust Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.