The Rust Programming Language

## Richard Feldman

Vendr, Inc.

### Check out a free preview of the full The Rust Programming Language course

The "Lifetimes Exercise" Lesson is part of the full, The Rust Programming Language course featured in this preview video. Here's what you'd learn in this lesson:

Students are instructed to call sum(), product(), and average() using references, return two slices, and use lifetime annotations to help keep track of the variables.

Preview
Close

### Transcript from the "Lifetimes Exercise" Lesson

[00:00:00]
>> So once again, we're calling some product and average to replace these equals zero values here without using clone. Or changing what these functions return. So we're not going to use any of the techniques we learned in part five with the ownership tricks. What we're going to do is we're going to just do this using references.

[00:00:15]
Now here, we've actually taken this a little bit further, and we're making things a little bit more complicated. So we also have these things called other numbers, which is like another vector of numbers. And we're making a tuple of slice one and slice two, which calls this thing called first three, which takes a slice of the first three numbers.

[00:00:33]
From numbers one as well as numbers to, sorry, from numbers as well as other numbers. So this is a case where we're actually going to end up with multiple different lifetimes coexisting, which is exactly why we're going to take more time for this one. So, some products in average, those are gonna be familiar from before.

[00:00:52]
We know exactly what to do to modify those things. But, this is kind of the the new stuff. So these first three function, its whole job is to grab the first three numbers and a slice out of numbers one and numbers two. And then return rather than returning vexed like this.

[00:01:06]
We wanna actually return two slices. And because these are potentially gonna have interesting lifetime stuff, we're gonna need to use the lifetime annotations for this here's a couple of tips on this. So here's a slice with lifetime added annotation. And also, here's some tips on how to introduce lifetime annotations to this function.

[00:01:26]
There's a couple of different ways to solve this one. And I realized that lifetimes are like a syntax, you really are not going to find it any other language but rust. So again, we'll take an extra give you some extra time on this one and then go through the solutions as usual.

### Learn Straight from the Experts Who Shape the Modern Web

• In-depth Courses