Simplification reference life-time

@sfackler @Ixrec

Sometimes during refactoring such code:

struct CompositeObject {
    obj: SomeType,
}

struct BigObject {
    composite_obj: CompositeObject,
    count: i32,
}

struct Application {
   big_obj: BigObject,
}

developer decides to make obj of SomeType as reference in CompositeObject type:

struct CompositeObject<'a> {
    obj: &'a SomeType,
}

struct BigObject<'a> {
    composite_obj: CompositeObject<'a>,
    count: i32,
}

struct Application<'a> {
   big_obj: BigObject<'a>,
}

Everywhere in composition hierarchy I need to write 'a ... most of the times it is just boilerplate code ...

What if instead of writing manually we will introduce the 'self life-time:

struct CompositeObject {
    obj: &'self SomeType,
}

struct BigObject {
    composite_obj: CompositeObject,
    count: i32,
}

struct Application {
   big_obj: BigObject,
}

Code much simpler and more maintainable than fighting with named life-times in composite hierarchy :wink:

Compiler underhood will generate the following code:

struct CompositeObject<'self> { // 'self is implicit life-time of each struct, like this in other languages
    obj: &'self SomeType,
}

struct BigObject<'self> { // 'self is implicit life-time of BigObject
    composite_obj: CompositeObject<'self>, // Assign 'self of BigObject to CompositeObject
    count: i32,
}

struct Application<'self> { // 'self is implicit life-time of Application
   big_obj: BigObject<'self>, // Assign 'self of Application to BigObject
}

@sfackler @Ixrec
What do you think about such simplification ?

1 Like