Skip to Main Content
Rust Programming Cookbook
book

Rust Programming Cookbook

by Claus Matzinger
October 2019
Intermediate to advanced content levelIntermediate to advanced
444 pages
10h 37m
English
Packt Publishing
Content preview from Rust Programming Cookbook

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Rust Web Programming

Rust Web Programming

Maxwell Flitton
The Complete Rust Programming Reference Guide

The Complete Rust Programming Reference Guide

Rahul Sharma, Vesa Kaihlavirta, Claus Matzinger

Publisher Resources

ISBN: 9781789530667Supplemental Content