The lifetime variable - '

We have two types of lifetime within Rust—implicit and explicit. We have seen the implicit functions plenty of times:

fn myfunction(pi: &f32) 
{ 
    // do something 
} 

The lifetime of the function is the length of time the code inside of the braces exists once it is called.

We also have an explicit lifetime, denoted by ' before the name:

fn expfunction<'a>(pi: &'a f32) 
{ 
    // do something 
} 

However, what exactly does the 'a mean?

It means, for the lifetime of a. The <> after expfunction means that the function is taking a generic parameter (these will all become clear in Chapter 9, Generics and Traits), but it means of a type. If you consider Vec, it is actually Vec<T>. When we create a vector of type f32, T becomes f32, so it's Vec<f32> when it comes to compile time. In the case of expfunction, T is 'a, and therefore the type inside the () has to also be 'a.

If we had another parameter within the <>, we would have <'a, 'b>(f: &'a f32, g: &'b i32), and so on.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset