Multiple lifetimes

Just like generic type parameters, we can specify multiple lifetimes if we have more than one reference that has different lifetimes. However, it can quickly become hairy when you have to juggle with more than one lifetime in your code. Most of the time, we can get away with just one lifetime in our structs or any of our functions. But there are cases where we'll need more than one lifetime annotations. For example, say we are building a decoder library that can parse binary files according to a schema and a given encoded stream of bytes. We have a Decoder object, which has a reference to a Schema object and a reference to a Reader type. Our Decoder definition will then look something like this:

// multiple_lifetimes.rs

struct Decoder<'a, 'b, S, R> {
schema: &'a S,
reader: &'b R
}

fn main() {}

In the preceding definition, it is quite possible that we get Reader from the network while the Schema is local, and so their lifetimes in code can be different. When we provide implementations for this Decoder, we can specify relations with it by lifetime subtyping, which we will explain next.

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

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