O'Reilly logo

Mastering Rust by Vesa Kaihlavirta

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Structs and struct fields

Whenever structs have references in them, we need to specify explicitly how long those references will live. The syntax is similar to that of the 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 the simplest form:

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

What we are saying here is that the num field must not refer to any u8 value that would live less long than the enclosing instance of the struct Foo. We are saying it explicitly again, as is the Rust way.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required