Lifetimes in user defined types

If a struct definition has fields that are reference to any type, we need to explicitly specify how long those references will live. The syntax is similar to that of function signatures: we first declare the lifetime names on the struct line, and then use them in the fields.

Here's what the syntax looks like in its simplest form:

//  lifetime_struct.rs

struct Number<'a> {
num: &'a u8
}

fn main() {
let _n = Number {num: &545};
}

The definition of Number lives as long as the reference for num.

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

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