OriBS
OriBS

Reputation: 732

Does returning a type with 'static tell the compiler this value doesn't have an associated lifetime or does it make that value static?

I have an enum with a "partial" lifetime: one of its variants contains a borrowed value, and another contains an owning value. I have a function which always returns an enum with the owning variant. In order to make the compiler happy, I have to state that the lifetime for the returned enum is 'static.

My question is about the real lifetime of the returned enum:

By stating that the lifetime is 'static, am I just guiding the compiler this enum doesn't have an associated lifetime or am I actually turning that instance to be static?

pub enum Sometimes<'a> {
    Own(u16),
    Borrow(&'a mut u16),
}

impl<'a> Sometimes<'a> {
    pub fn from_u16(data: u16) -> Sometimes<'static> {
        Sometimes::Own(data)
    }
}

Upvotes: 1

Views: 106

Answers (1)

user2722968
user2722968

Reputation: 16485

It's exactly what it seems to be: You are telling the compiler that the type returned by from_u16 will have a lifetime of 'static associated with it. This lifetime is carried with the enum type itself, not a specific variant.

The type Sometimes<'static> is different from any other type Sometime<'a> unless 'a is 'static. For example, you may not be able to call/return from a function fn foobar<'a>(foo: Sometime<'a>) -> ... with values returned from from_u16 unless 'a can be made to be 'static (the compiler will yell at you for promising a generic lifetime 'a but using a specific lifetime 'static and not being able to prove that 'a is in fact 'static).

Another consequence is that you can't change the value of the thing returned by from_u16 to Sometimes::Borrow(&mut u16) unless that reference is 'static (which may be what you want). Consider a function foobar as above, where the compiler figured that 'a is 'static as it was passed what was returned from from_u16. Now some code somewhere mutates the values to be a Sometimes::Borrow. This is safe only if the lifetime associated with Sometimes::Borrow is still 'static all along, otherwise foobar now handles what it supposed was a 'static lifetime but is, in fact, a dangling reference. That's a paddling.

So no, you can't guide the compiler that there is a variant of enum where the lifetime does not matter. The instance returned is not 'static by itself, it just carries an associated lifetime of 'static wherever it goes and the compiler will complain if you try to return some generic lifetime but actually return 'static.

Upvotes: 1

Related Questions