Lifetime within an struct

As seen in Chapter 7, Structs, within Rust have a special purpose and they can also take multiple types within them and can be extended as much as required with as many parameters as required. Let's consider the following piece of code as an example:

struct MyStruct 
{ 
    a: i32, 
    b: f32, 
    c: bool, 
} 

The preceding code creates a struct called MyStruct with three properties called a, b, and c. When an instance of mystruct is called into scope, the elements within struct can be readily accessed. If we want struct to be able to take a lifetime variable, we will have to both explicitly ask struct to take that lifetime variable and then allocate it to an element, as shown in the following code:

struct<'a> MyStruct 
{ 
    lifetimevar: &'a f32, 
    nvar: i32, 
} 

With the lifetime variable in there, we can be assured that the structure cannot outlive the f32 reference it was passed to.

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

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