Skip to content

Adding Lifetime to Struct

Sewen Thy edited this page Sep 21, 2022 · 3 revisions

Adding lifetime parameters to a struct in Rust requires a lot of changes to be applied correctly to functions and other structs using the updated struct. This example shows a struct Foo that has its fields updated from literal values to references with possibly different lifetimes FooUpdated so the function that initialize Foo: make_foo needs to be updated such that it takes in references of possibly different lifetime to initialize FooUpdated: make_foo_updated.

pub struct Foo {x: i32, y: i32}

pub fn make_foo(x: &i32, y: &i32) -> Foo {
    Foo{x: *x, y: *y}
}

To change Foo to include possibly different lifetimes, Foo lifetimes need to be annotated:

pub struct FooUpdated<'a, 'b> {x: &'a i32, y: &'b i32}

And its initialization function also needs to be annotated and updated:

pub fn make_foo_updated<'a, 'b>(x: &'a i32, y: &'b i32) -> FooUpdated<'a, 'b>{
    FooUpdated{x, y}
}